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
systems.rs
// будем юзать Behaviour Tree AI //Главный скрипт работает по системе выбор-условие-действие (selector-condition-action). //Выбор — своеобразный аналог оператора switch() в языках программирования. // В «теле» элемента выбора происходит выбор одного из заданных наборов действий // в зависимости от условия. //Условие — проверка истинности заданного условия. // Используется в начале каждого набора действий внутри элемента выбора. // Если условие истинно — выполняется данный набор действий и выбор завершается. // Если нет — происходит переход к следующему набору действий //Действие — скрипт, запускающий другой скрипт (действие) с заданными параметрами. // *В BT AI существует понятие базовых действий. /* SelectorBegin('AI Role 1'); SequenceBegin('Атака'); //видим врага и знаем его id Condition(SeeEnemy && Enemy>0); //смомтрим на него Action( Action_LookAt, point_direction(x,y, Enemy.x, Enemy.y)); //стреляем в сторону врага 2 раза Action( Action_Shoot, point_direction(x,y, Enemy.x, Enemy.y), 2); SelectorBegin('Подходим на оптимальное растояние'); //или SequenceBegin('Враг слишком далеко'); Condition(point_distance(x,y, Enemy.x, Enemy.y)>256); Action(Action_MoveTo, Enemy.x-lengthdir_x(128, direction), Enemy.y-lengthdir_y(128, direction), highSpeed); SequenceEnd(); //или SequenceBegin('Враг слишком близко'); Condition(point_distance(x,y, Enemy.x, Enemy.y)<64); //идем назад Action(Action_MoveTo, x-lengthdir_x(64, direction), y-lengthdir_y(64, direction), highSpeed); SequenceEnd(); SequenceBegin('маневр'); //иначе просто маневрируем, чтобы сложнее было попасть Action( Action_MoveTo, x+irandom_range(-64, 64), y+irandom_range(-64, 64), highSpeed); SequenceEnd(); SelectorEnd(); //стреляем в сторону врага 4 раза Action(Action_Shoot, point_direction(x,y, Enemy.x, Enemy.y), 2); SequenceEnd(); SelectorEnd(); */ //Selector — оператор выбора набора действий //Sequence — набор действий //Condition — проверка условия //Action — действие. вызов скрипта(первый аргумент) с параметрами (остальные аргументы) /* http://www.pvsm.ru/robototehnika/161885/print/ Узлы BT называют [10] задачами или поведениями. Каждая задача может иметь четыре состояния: «Успех», если задача выполнена успешно; - выкинуть нахер, заменитьт ошибкой. «Неудача», если условие не выполнено или задача, по какой-то причине, невыполнима; «В работе», если задача запущена в работу и ожидает завершения «Ошибка», если в программе возникает неизвестная ошибка. Результат работы любого узла всегда передается родительскому узлу, расположенному на уровень выше. Дерево просматривается с самого верхнего узла – корня. От него производится поиск в глубину начиная с левой ветви дерева. Если у одного узла есть несколько подзадач, они исполняются слева направо. Среди узлов выделяют следующие типы: -действие (action), -узел исполнения последовательности (sequence), -параллельный узел (parallel), -селектор (selector), -условие (condition), -инвертор (inverter). Действие представляет собой запись переменных или какое-либо движение. Узлы последовательностей поочередно исполняют поведения каждого дочернего узла до тех пор, пока один из них не выдаст значение «Неудача», «В работе» или «Ошибка». Если этого не произошло, возвращает значение «Успех». Узлы параллельных действий исполняют поведения дочерних узлов до тех пор, пока заданное количество из них не вернет статусы «Неудача» или «Успех». Селекторы поочередно исполняют поведения каждого дочернего узла до тех пор, пока один из них не выдаст значение «Успех», «В работе» или «Ошибка». Если этого не произошло, возвращает значение «Неудача». Условия содержат критерий, по которому определяется исход, и переменную. Например, условие «Есть ли в этой комнате человек?» перебирает все объекты в комнате и сравнивает их с переменной «Человек». Узлы инверсии выполняют функцию оператора NOT. */ use tinyecs::*; use time::{PreciseTime, Duration}; use WORLD_SPEED; use ::manager::components::Position; use ::monster::components::MonsterClass; use ::monster::components::MonsterAttributes; use ::monster::components::SelectionTree; use ::monster::components::BehaviourEvent; use ::monster::components::BehaviourState; /// Система восприятия pub struct _PerceptionSystem; // тут типа чекает окружение, и помечает объекты что попадают в поле зения. impl System for _PerceptionSystem { fn aspect(&self) -> Aspect { aspect_all!(MonsterClass) } fn process_one(&mut self, _entity: &mut Entity) { // здесь тоже меняются события. // сканируем вокруг, может есть еда или вода или др. монстр или ОБОРИГЕН! } } /// Выбиральщик состояний дерева поведения // используя код программатора SelectionTree, переключает состояния. pub struct SelectorSystem; impl System for SelectorSystem { fn aspect(&self) -> Aspect { aspect_all!(MonsterClass, SelectionTree, BehaviourEvent, BehaviourState) } // fn process_no_entities(&mut self) { // println!("instaced buffer render system must work, but no entities!"); // } // fn process_no_data(&mut self) { // println!("instaced buffer render system must work, but no data!"); // } fn process_one(&mut self, entity: &mut Entity) { let mut selection_tree = entity.get_component::<SelectionTree>(); let mut behaviour_state = entity.get_component::<BehaviourState>(); // состояние let behaviour_event = entity.get_component::<BehaviourEvent>(); // события let len = selection_tree.selector.len(); if len > 0 { // ткущий узел. if selection_tree.curr_selector < 0i32 { selection_tree.curr_selector = 0i32; println!("ошибка/инициализация текущего указателя, теперь он {}", 0i32); } else { /*event, state let sel = vec![[6, 2], [5, 1]];*/ let index: usize = selection_tree.curr_selector as usize; let curr_cell = selection_tree.selector[index]; //[6, 2] let v_event = curr_cell[0]; let v_state = curr_cell[1]; // проверить нет ли ошибки в селекторе/программаторе. или первый запуск/инициализация. let curr_event = behaviour_event.event; // считываем текущий событие/event if curr_event == v_event { // меняем состояние, на соответствующее. behaviour_state.state = v_state; println!("обнаружено событие {}", v_event); println!("переключаю состояние на {}", v_state); // сдвигаем curr_selector, переходим к сл. ячейке. let shl: i32 = (len - 1) as i32; if selection_tree.curr_selector < shl { selection_tree.curr_selector += 1; } else { selection_tree.curr_selector = 0; } } } } } } /// Активатор. Приводит в действие. // считывает состояние и выполняет его, либо продолжает выполнение. // система поведения. pub struct BehaviorSystem { pub behavior_time: PreciseTime, } impl System for BehaviorSystem { fn aspect(&self) -> Aspect { aspect_all!(MonsterClass, BehaviourState, Position) } fn process_one(&mut self, entity: &mut Entity) { // смотрит текущее состояние и выполняет действие. // тут заставляем монстра ходить, пить, искать. // 0. Инициализация, ошибка. // 1. Сон. Монстр ждет, в этот момент с ним ничего не происходит. // 2. Бодрствование. Случайное перемещение по полигону. // 3. Поиск пищи. // 4. Поиск воды. // 5. Прием пищи. // 6. Прием воды. // 7. Перемещение к цели. // 8. Проверка достижения цели. if self.behavior_time.to(PreciseTime::now()) > Duration::seconds(5 * WORLD_SPEED) { let behaviour_state = entity.get_component::<BehaviourState>(); // состояние let mut position = entity.get_component::<Position>(); match behaviour_state.state { 1 => { println!("...zzz..."); }, 2 => { // тут заставляем монстра ходить туда-сюда, бесцельно, куда подует) if position.x > (position.y * 2f32) && position.y < 139f32 { position.y += 1f32; } else if position.x < 139f32 { position.x += 1f32; } println!("x:{}, y:{}", position.x, position.y); /* движение по овальной траектории. x = x_+x_radius*cos(r_ang+2); y = y_+y_radius*sin(r_ang); X1 = X + R * 0.5; Y1 = Y + 1.3 * R * 0.8; 0.5 это синус 30 0.8 это косинус 30 R - хз. например 20 клеток. X, Y - это текущие координаты. */ // let x1: f32 = position.x + 20f32 * 0.5; // let y1: f32 = position.y + 1.3f32 * 20f32 *0.8; // position.x = x1; // position.y = y1; // println!("x:{}, y:{}", position.x, position.y); }, _ => {}, } // фиксируем текущее время self.behavior_time = PreciseTime::now(); } } } /// Генерация событий // Создаем события, проверяем параметры. pub struct EventSystem { pub event_time: PreciseTime, pub event_last: u32, // 0 - инициализация/ошибка } impl System for EventSystem { fn aspect(&self) -> Aspect { aspect_all!(MonsterAttributes, BehaviourEvent) } fn process_one(&mut self, entity: &mut Entity) { // 0. Инициализация, ошибка. // 1. Обнаружена еда. // 2. Обнаружена вода. // 3. Наступил голод. // 4. Наступила жажда. // 5. Утомился. // 6. Нет событий. // 7. Монстр насытился. // 8. Монстр напился.
behaviour_event.event = 6; println!("ошибка/инициализация текущего события, теперь он {}", 6); } else if monster_attr.power < 960 && self.event_last != 5 { behaviour_event.event = 5; // наступает событие - УСТАЛ self.event_last = behaviour_event.event; println!("Новое событие: монстр устал."); } else if monster_attr.power > 990 && self.event_last != 6 { behaviour_event.event = 6; self.event_last = behaviour_event.event; println!("Новое событие: монстр отдохнул."); } // фиксируем текущее время self.event_time = PreciseTime::now(); } } }
if self.event_time.to(PreciseTime::now()) > Duration::seconds(WORLD_SPEED) { let mut behaviour_event = entity.get_component::<BehaviourEvent>(); // события let monster_attr = entity.get_component::<MonsterAttributes>(); // события if behaviour_event.event == 0 { // проверяем ошибки/инициализация
random_line_split
add.go
package cmd import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "k8s.io/helm/pkg/repo" "github.com/covexo/devspace/pkg/util/stdinutil" "github.com/covexo/devspace/pkg/util/tar" "github.com/covexo/devspace/pkg/util/yamlutil" helmClient "github.com/covexo/devspace/pkg/devspace/clients/helm" "github.com/covexo/devspace/pkg/devspace/clients/kubectl" "github.com/covexo/devspace/pkg/devspace/config/configutil" "github.com/covexo/devspace/pkg/devspace/config/v1" "github.com/covexo/devspace/pkg/util/log" "github.com/russross/blackfriday" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" ) // AddCmd holds the information needed for the add command type AddCmd struct { flags *AddCmdFlags syncFlags *addSyncCmdFlags portFlags *addPortCmdFlags packageFlags *addPackageFlags dsConfig *v1.DevSpaceConfig } // AddCmdFlags holds the possible flags for the add command type AddCmdFlags struct { } type addSyncCmdFlags struct { ResourceType string Selector string LocalPath string ContainerPath string ExcludedPaths string } type addPortCmdFlags struct { ResourceType string Selector string } type addPackageFlags struct { AppVersion string ChartVersion string SkipQuestion bool } func init() { cmd := &AddCmd{ flags: &AddCmdFlags{}, syncFlags: &addSyncCmdFlags{}, portFlags: &addPortCmdFlags{}, packageFlags: &addPackageFlags{}, } addCmd := &cobra.Command{ Use: "add", Short: "Change the devspace configuration", Long: ` ####################################################### #################### devspace add ##################### ####################################################### You can change the following configuration with the add command: * Sync paths (sync) * Forwarded ports (port) ####################################################### `, Args: cobra.NoArgs, } rootCmd.AddCommand(addCmd) addSyncCmd := &cobra.Command{ Use: "sync", Short: "Add a sync path to the devspace", Long: ` ####################################################### ################# devspace add sync ################### ####################################################### Add a sync path to the devspace How to use: devspace add sync --local=app --container=/app ####################################################### `, Args: cobra.NoArgs, Run: cmd.RunAddSync, } addCmd.AddCommand(addSyncCmd) addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type") addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)") addSyncCmd.MarkFlagRequired("local") addSyncCmd.MarkFlagRequired("container") addPortCmd := &cobra.Command{ Use: "port", Short: "Add a new port forward configuration", Long: ` ####################################################### ################ devspace add port #################### ####################################################### Add a new port mapping that should be forwarded to the devspace (format is local:remote comma separated): devspace add port 8080:80,3000 ####################################################### `, Args: cobra.ExactArgs(1), Run: cmd.RunAddPort, } addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type") addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addCmd.AddCommand(addPortCmd) addPackageCmd := &cobra.Command{ Use: "package", Short: "Add a helm chart", Long: ` ####################################################### ############### devspace add package ################## ####################################################### Adds an existing helm chart to the devspace (run 'devspace add package' to display all available helm charts) Examples: devspace add package devspace add package mysql devspace add package mysql --app-version=5.7.14 devspace add package mysql --chart-version=0.10.3 ####################################################### `, Run: cmd.RunAddPackage, } addPackageCmd.Flags().StringVar(&cmd.packageFlags.AppVersion, "app-version", "", "App version") addPackageCmd.Flags().StringVar(&cmd.packageFlags.ChartVersion, "chart-version", "", "Chart version") addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser") addCmd.AddCommand(addPackageCmd) } // RunAddPackage executes the add package command logic func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) { kubectl, err := kubectl.NewClient() if err != nil { log.Fatalf("Unable to create new kubectl client: %v", err) } helm, err := helmClient.NewClient(kubectl, false) if err != nil { log.Fatalf("Error initializing helm client: %v", err) } if len(args) != 1 { helm.PrintAllAvailableCharts() return } log.StartWait("Search Chart") repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion) log.StopWait() if err != nil { log.Fatal(err) } log.Done("Chart found") cwd, err := os.Getwd() if err != nil { log.Fatal(err) } requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml") _, err = os.Stat(requirementsFile) if os.IsNotExist(err) { entry := "dependencies:\n" + "- name: \"" + version.GetName() + "\"\n" + " version: \"" + version.GetVersion() + "\"\n" + " repository: \"" + repo.URL + "\"\n" err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600) if err != nil { log.Fatal(err) } } else { yamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", requirementsFile, err) } dependenciesArr := []interface{}{} if dependencies, ok := yamlContents["dependencies"]; ok { dependenciesArr, ok = dependencies.([]interface{}) if ok == false { log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile) } } dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{ "name": version.GetName(), "version": version.GetVersion(), "repository": repo.URL, }) yamlContents["dependencies"] = dependenciesArr err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile) if err != nil { log.Fatal(err) } } log.StartWait("Update chart dependencies") err = helm.UpdateDependencies(filepath.Join(cwd, "chart")) log.StopWait() if err != nil { log.Fatal(err) } // Check if key already exists valuesYaml := filepath.Join(cwd, "chart", "values.yaml") valuesYamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", valuesYaml, err) } if _, ok := valuesYamlContents[version.GetName()]; ok == false { f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil { log.Fatal(err) } } log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName()) cmd.showReadme(version) } func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) { cwd, err := os.Getwd() if err != nil { log.Fatal(err) } if cmd.packageFlags.SkipQuestion { return } showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{ Question: "Do you want to open the package README? (y|n)", DefaultValue: "y", ValidationRegexPattern: "^(y|n)", }) if showReadme == "n" { return } content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md") if err != nil
output := blackfriday.MarkdownCommon([]byte(content)) f, err := os.OpenFile(filepath.Join(os.TempDir(), "Readme.html"), os.O_RDWR|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() _, err = f.Write(output) if err != nil { log.Fatal(err) } f.Close() open.Start(f.Name()) } // RunAddSync executes the add sync command logic func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.syncFlags.Selector == "" { cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } excludedPaths := make([]string, 0, 0) if cmd.syncFlags.ExcludedPaths != "" { excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",") for _, v := range excludedPathStrings { excludedPath := strings.TrimSpace(v) excludedPaths = append(excludedPaths, excludedPath) } } workdir, err := os.Getwd() if err != nil { log.Fatalf("Unable to determine current workdir: %s", err.Error()) } cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir) cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./") if cmd.syncFlags.ContainerPath[0] != '/' { log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.") } syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{ ResourceType: configutil.String(cmd.syncFlags.ResourceType), LabelSelector: &labelSelectorMap, ContainerPath: configutil.String(cmd.syncFlags.ContainerPath), LocalSubPath: configutil.String(cmd.syncFlags.LocalPath), ExcludePaths: &excludedPaths, }) config.DevSpace.Sync = &syncConfig err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } // RunAddPort executes the add port command logic func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.portFlags.Selector == "" { cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } portMappings, err := parsePortMappings(args[0]) if err != nil { log.Fatalf("Error parsing port mappings: %s", err.Error()) } cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings) err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) { config := configutil.GetConfig(false) // Check if we should add to existing port mapping for _, v := range *config.DevSpace.PortForwarding { var selectors map[string]*string if v.LabelSelector != nil { selectors = *v.LabelSelector } else { selectors = map[string]*string{} } if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) { portMap := append(*v.PortMappings, portMappings...) v.PortMappings = &portMap return } } portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{ ResourceType: configutil.String(cmd.portFlags.ResourceType), LabelSelector: &labelSelectorMap, PortMappings: &portMappings, }) config.DevSpace.PortForwarding = &portMap } func isMapEqual(map1 map[string]*string, map2 map[string]*string) bool { if len(map1) != len(map2) { return false } for k, v := range map1 { if *map2[k] != *v { return false } } return true } func parsePortMappings(portMappingsString string) ([]*v1.PortMapping, error) { portMappings := make([]*v1.PortMapping, 0, 1) portMappingsSplitted := strings.Split(portMappingsString, ",") for _, v := range portMappingsSplitted { portMapping := strings.Split(v, ":") if len(portMapping) != 1 && len(portMapping) != 2 { return nil, fmt.Errorf("Error parsing port mapping: %s", v) } portMappingStruct := &v1.PortMapping{} firstPort, err := strconv.Atoi(portMapping[0]) if err != nil { return nil, err } if len(portMapping) == 1 { portMappingStruct.LocalPort = &firstPort portMappingStruct.RemotePort = portMappingStruct.LocalPort } else { portMappingStruct.LocalPort = &firstPort secondPort, err := strconv.Atoi(portMapping[1]) if err != nil { return nil, err } portMappingStruct.RemotePort = &secondPort } portMappings = append(portMappings, portMappingStruct) } return portMappings, nil } func parseSelectors(selectorString string) (map[string]*string, error) { selectorMap := make(map[string]*string) if selectorString == "" { return selectorMap, nil } selectors := strings.Split(selectorString, ",") for _, v := range selectors { keyValue := strings.Split(v, "=") if len(keyValue) != 2 { return nil, fmt.Errorf("Wrong selector format: %s", selectorString) } selector := strings.TrimSpace(keyValue[1]) selectorMap[strings.TrimSpace(keyValue[0])] = &selector } return selectorMap, nil }
{ log.Fatal(err) }
conditional_block
add.go
package cmd import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "k8s.io/helm/pkg/repo" "github.com/covexo/devspace/pkg/util/stdinutil" "github.com/covexo/devspace/pkg/util/tar" "github.com/covexo/devspace/pkg/util/yamlutil" helmClient "github.com/covexo/devspace/pkg/devspace/clients/helm" "github.com/covexo/devspace/pkg/devspace/clients/kubectl" "github.com/covexo/devspace/pkg/devspace/config/configutil" "github.com/covexo/devspace/pkg/devspace/config/v1" "github.com/covexo/devspace/pkg/util/log" "github.com/russross/blackfriday" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" ) // AddCmd holds the information needed for the add command type AddCmd struct { flags *AddCmdFlags syncFlags *addSyncCmdFlags portFlags *addPortCmdFlags packageFlags *addPackageFlags dsConfig *v1.DevSpaceConfig } // AddCmdFlags holds the possible flags for the add command type AddCmdFlags struct { } type addSyncCmdFlags struct { ResourceType string Selector string LocalPath string ContainerPath string ExcludedPaths string } type addPortCmdFlags struct { ResourceType string Selector string } type addPackageFlags struct { AppVersion string ChartVersion string SkipQuestion bool } func init() { cmd := &AddCmd{ flags: &AddCmdFlags{}, syncFlags: &addSyncCmdFlags{}, portFlags: &addPortCmdFlags{}, packageFlags: &addPackageFlags{}, } addCmd := &cobra.Command{ Use: "add", Short: "Change the devspace configuration", Long: ` ####################################################### #################### devspace add ##################### ####################################################### You can change the following configuration with the add command: * Sync paths (sync) * Forwarded ports (port) ####################################################### `, Args: cobra.NoArgs, } rootCmd.AddCommand(addCmd) addSyncCmd := &cobra.Command{ Use: "sync", Short: "Add a sync path to the devspace", Long: ` ####################################################### ################# devspace add sync ################### ####################################################### Add a sync path to the devspace How to use: devspace add sync --local=app --container=/app ####################################################### `, Args: cobra.NoArgs, Run: cmd.RunAddSync, } addCmd.AddCommand(addSyncCmd) addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type") addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)") addSyncCmd.MarkFlagRequired("local") addSyncCmd.MarkFlagRequired("container") addPortCmd := &cobra.Command{ Use: "port", Short: "Add a new port forward configuration", Long: ` ####################################################### ################ devspace add port #################### ####################################################### Add a new port mapping that should be forwarded to the devspace (format is local:remote comma separated): devspace add port 8080:80,3000 ####################################################### `, Args: cobra.ExactArgs(1), Run: cmd.RunAddPort, } addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type") addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addCmd.AddCommand(addPortCmd) addPackageCmd := &cobra.Command{ Use: "package", Short: "Add a helm chart", Long: ` ####################################################### ############### devspace add package ################## ####################################################### Adds an existing helm chart to the devspace (run 'devspace add package' to display all available helm charts) Examples: devspace add package devspace add package mysql devspace add package mysql --app-version=5.7.14 devspace add package mysql --chart-version=0.10.3 ####################################################### `, Run: cmd.RunAddPackage, } addPackageCmd.Flags().StringVar(&cmd.packageFlags.AppVersion, "app-version", "", "App version") addPackageCmd.Flags().StringVar(&cmd.packageFlags.ChartVersion, "chart-version", "", "Chart version") addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser") addCmd.AddCommand(addPackageCmd) } // RunAddPackage executes the add package command logic func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) { kubectl, err := kubectl.NewClient() if err != nil { log.Fatalf("Unable to create new kubectl client: %v", err) } helm, err := helmClient.NewClient(kubectl, false) if err != nil { log.Fatalf("Error initializing helm client: %v", err) } if len(args) != 1 { helm.PrintAllAvailableCharts() return } log.StartWait("Search Chart") repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion) log.StopWait() if err != nil { log.Fatal(err) } log.Done("Chart found") cwd, err := os.Getwd() if err != nil { log.Fatal(err) } requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml") _, err = os.Stat(requirementsFile) if os.IsNotExist(err) { entry := "dependencies:\n" + "- name: \"" + version.GetName() + "\"\n" + " version: \"" + version.GetVersion() + "\"\n" + " repository: \"" + repo.URL + "\"\n" err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600) if err != nil { log.Fatal(err) } } else { yamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", requirementsFile, err) } dependenciesArr := []interface{}{} if dependencies, ok := yamlContents["dependencies"]; ok { dependenciesArr, ok = dependencies.([]interface{}) if ok == false { log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile) } } dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{ "name": version.GetName(), "version": version.GetVersion(), "repository": repo.URL, }) yamlContents["dependencies"] = dependenciesArr err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile) if err != nil { log.Fatal(err) } } log.StartWait("Update chart dependencies") err = helm.UpdateDependencies(filepath.Join(cwd, "chart")) log.StopWait() if err != nil { log.Fatal(err) } // Check if key already exists valuesYaml := filepath.Join(cwd, "chart", "values.yaml") valuesYamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", valuesYaml, err) } if _, ok := valuesYamlContents[version.GetName()]; ok == false { f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil { log.Fatal(err) } } log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName()) cmd.showReadme(version) } func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) { cwd, err := os.Getwd() if err != nil { log.Fatal(err) } if cmd.packageFlags.SkipQuestion { return } showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{ Question: "Do you want to open the package README? (y|n)", DefaultValue: "y", ValidationRegexPattern: "^(y|n)", }) if showReadme == "n" { return } content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md") if err != nil { log.Fatal(err) } output := blackfriday.MarkdownCommon([]byte(content)) f, err := os.OpenFile(filepath.Join(os.TempDir(), "Readme.html"), os.O_RDWR|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() _, err = f.Write(output) if err != nil { log.Fatal(err) } f.Close() open.Start(f.Name()) } // RunAddSync executes the add sync command logic func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.syncFlags.Selector == "" { cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } excludedPaths := make([]string, 0, 0) if cmd.syncFlags.ExcludedPaths != "" { excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",") for _, v := range excludedPathStrings { excludedPath := strings.TrimSpace(v) excludedPaths = append(excludedPaths, excludedPath) } } workdir, err := os.Getwd() if err != nil { log.Fatalf("Unable to determine current workdir: %s", err.Error()) } cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir) cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./") if cmd.syncFlags.ContainerPath[0] != '/' { log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.") } syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{ ResourceType: configutil.String(cmd.syncFlags.ResourceType), LabelSelector: &labelSelectorMap, ContainerPath: configutil.String(cmd.syncFlags.ContainerPath), LocalSubPath: configutil.String(cmd.syncFlags.LocalPath), ExcludePaths: &excludedPaths, }) config.DevSpace.Sync = &syncConfig err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } // RunAddPort executes the add port command logic func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.portFlags.Selector == "" { cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } portMappings, err := parsePortMappings(args[0]) if err != nil { log.Fatalf("Error parsing port mappings: %s", err.Error()) } cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings) err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) { config := configutil.GetConfig(false) // Check if we should add to existing port mapping for _, v := range *config.DevSpace.PortForwarding { var selectors map[string]*string if v.LabelSelector != nil { selectors = *v.LabelSelector } else { selectors = map[string]*string{} } if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) { portMap := append(*v.PortMappings, portMappings...) v.PortMappings = &portMap return } } portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{ ResourceType: configutil.String(cmd.portFlags.ResourceType), LabelSelector: &labelSelectorMap, PortMappings: &portMappings, }) config.DevSpace.PortForwarding = &portMap } func isMapEqual(map1 map[string]*string, map2 map[string]*string) bool { if len(map1) != len(map2) { return false } for k, v := range map1 { if *map2[k] != *v { return false } } return true } func parsePortMappings(portMappingsString string) ([]*v1.PortMapping, error)
func parseSelectors(selectorString string) (map[string]*string, error) { selectorMap := make(map[string]*string) if selectorString == "" { return selectorMap, nil } selectors := strings.Split(selectorString, ",") for _, v := range selectors { keyValue := strings.Split(v, "=") if len(keyValue) != 2 { return nil, fmt.Errorf("Wrong selector format: %s", selectorString) } selector := strings.TrimSpace(keyValue[1]) selectorMap[strings.TrimSpace(keyValue[0])] = &selector } return selectorMap, nil }
{ portMappings := make([]*v1.PortMapping, 0, 1) portMappingsSplitted := strings.Split(portMappingsString, ",") for _, v := range portMappingsSplitted { portMapping := strings.Split(v, ":") if len(portMapping) != 1 && len(portMapping) != 2 { return nil, fmt.Errorf("Error parsing port mapping: %s", v) } portMappingStruct := &v1.PortMapping{} firstPort, err := strconv.Atoi(portMapping[0]) if err != nil { return nil, err } if len(portMapping) == 1 { portMappingStruct.LocalPort = &firstPort portMappingStruct.RemotePort = portMappingStruct.LocalPort } else { portMappingStruct.LocalPort = &firstPort secondPort, err := strconv.Atoi(portMapping[1]) if err != nil { return nil, err } portMappingStruct.RemotePort = &secondPort } portMappings = append(portMappings, portMappingStruct) } return portMappings, nil }
identifier_body
add.go
package cmd import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "k8s.io/helm/pkg/repo" "github.com/covexo/devspace/pkg/util/stdinutil" "github.com/covexo/devspace/pkg/util/tar" "github.com/covexo/devspace/pkg/util/yamlutil" helmClient "github.com/covexo/devspace/pkg/devspace/clients/helm" "github.com/covexo/devspace/pkg/devspace/clients/kubectl" "github.com/covexo/devspace/pkg/devspace/config/configutil" "github.com/covexo/devspace/pkg/devspace/config/v1" "github.com/covexo/devspace/pkg/util/log" "github.com/russross/blackfriday" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" ) // AddCmd holds the information needed for the add command type AddCmd struct { flags *AddCmdFlags syncFlags *addSyncCmdFlags portFlags *addPortCmdFlags packageFlags *addPackageFlags dsConfig *v1.DevSpaceConfig } // AddCmdFlags holds the possible flags for the add command type AddCmdFlags struct { } type addSyncCmdFlags struct { ResourceType string Selector string LocalPath string ContainerPath string ExcludedPaths string } type addPortCmdFlags struct { ResourceType string Selector string } type addPackageFlags struct { AppVersion string ChartVersion string SkipQuestion bool } func init() { cmd := &AddCmd{ flags: &AddCmdFlags{}, syncFlags: &addSyncCmdFlags{}, portFlags: &addPortCmdFlags{}, packageFlags: &addPackageFlags{}, } addCmd := &cobra.Command{ Use: "add", Short: "Change the devspace configuration", Long: ` ####################################################### #################### devspace add ##################### ####################################################### You can change the following configuration with the add command: * Sync paths (sync) * Forwarded ports (port) ####################################################### `, Args: cobra.NoArgs, } rootCmd.AddCommand(addCmd) addSyncCmd := &cobra.Command{ Use: "sync", Short: "Add a sync path to the devspace", Long: ` ####################################################### ################# devspace add sync ################### ####################################################### Add a sync path to the devspace How to use: devspace add sync --local=app --container=/app ####################################################### `, Args: cobra.NoArgs, Run: cmd.RunAddSync, } addCmd.AddCommand(addSyncCmd) addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type") addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)") addSyncCmd.MarkFlagRequired("local") addSyncCmd.MarkFlagRequired("container") addPortCmd := &cobra.Command{ Use: "port", Short: "Add a new port forward configuration", Long: ` ####################################################### ################ devspace add port #################### ####################################################### Add a new port mapping that should be forwarded to the devspace (format is local:remote comma separated): devspace add port 8080:80,3000 ####################################################### `, Args: cobra.ExactArgs(1), Run: cmd.RunAddPort, } addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type") addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addCmd.AddCommand(addPortCmd) addPackageCmd := &cobra.Command{ Use: "package", Short: "Add a helm chart", Long: ` ####################################################### ############### devspace add package ################## ####################################################### Adds an existing helm chart to the devspace (run 'devspace add package' to display all available helm charts) Examples: devspace add package devspace add package mysql devspace add package mysql --app-version=5.7.14 devspace add package mysql --chart-version=0.10.3 ####################################################### `, Run: cmd.RunAddPackage, } addPackageCmd.Flags().StringVar(&cmd.packageFlags.AppVersion, "app-version", "", "App version") addPackageCmd.Flags().StringVar(&cmd.packageFlags.ChartVersion, "chart-version", "", "Chart version") addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser") addCmd.AddCommand(addPackageCmd) } // RunAddPackage executes the add package command logic func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) { kubectl, err := kubectl.NewClient() if err != nil { log.Fatalf("Unable to create new kubectl client: %v", err) } helm, err := helmClient.NewClient(kubectl, false) if err != nil { log.Fatalf("Error initializing helm client: %v", err) } if len(args) != 1 { helm.PrintAllAvailableCharts() return } log.StartWait("Search Chart") repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion) log.StopWait() if err != nil { log.Fatal(err) } log.Done("Chart found") cwd, err := os.Getwd() if err != nil { log.Fatal(err) } requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml") _, err = os.Stat(requirementsFile) if os.IsNotExist(err) { entry := "dependencies:\n" + "- name: \"" + version.GetName() + "\"\n" + " version: \"" + version.GetVersion() + "\"\n" + " repository: \"" + repo.URL + "\"\n" err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600) if err != nil { log.Fatal(err) } } else { yamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", requirementsFile, err) } dependenciesArr := []interface{}{} if dependencies, ok := yamlContents["dependencies"]; ok { dependenciesArr, ok = dependencies.([]interface{}) if ok == false { log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile) } } dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{ "name": version.GetName(), "version": version.GetVersion(), "repository": repo.URL, }) yamlContents["dependencies"] = dependenciesArr err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile) if err != nil { log.Fatal(err) } } log.StartWait("Update chart dependencies") err = helm.UpdateDependencies(filepath.Join(cwd, "chart")) log.StopWait() if err != nil { log.Fatal(err) } // Check if key already exists valuesYaml := filepath.Join(cwd, "chart", "values.yaml") valuesYamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", valuesYaml, err) } if _, ok := valuesYamlContents[version.GetName()]; ok == false { f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil { log.Fatal(err) } } log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName()) cmd.showReadme(version) } func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) { cwd, err := os.Getwd() if err != nil { log.Fatal(err) } if cmd.packageFlags.SkipQuestion { return } showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{ Question: "Do you want to open the package README? (y|n)", DefaultValue: "y", ValidationRegexPattern: "^(y|n)", }) if showReadme == "n" { return } content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md") if err != nil { log.Fatal(err) } output := blackfriday.MarkdownCommon([]byte(content)) f, err := os.OpenFile(filepath.Join(os.TempDir(), "Readme.html"), os.O_RDWR|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() _, err = f.Write(output) if err != nil { log.Fatal(err) } f.Close() open.Start(f.Name()) } // RunAddSync executes the add sync command logic func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.syncFlags.Selector == "" { cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } excludedPaths := make([]string, 0, 0) if cmd.syncFlags.ExcludedPaths != "" { excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",") for _, v := range excludedPathStrings { excludedPath := strings.TrimSpace(v) excludedPaths = append(excludedPaths, excludedPath) } } workdir, err := os.Getwd() if err != nil { log.Fatalf("Unable to determine current workdir: %s", err.Error()) } cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir) cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./") if cmd.syncFlags.ContainerPath[0] != '/' { log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.") } syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{ ResourceType: configutil.String(cmd.syncFlags.ResourceType), LabelSelector: &labelSelectorMap, ContainerPath: configutil.String(cmd.syncFlags.ContainerPath), LocalSubPath: configutil.String(cmd.syncFlags.LocalPath), ExcludePaths: &excludedPaths, }) config.DevSpace.Sync = &syncConfig err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } // RunAddPort executes the add port command logic func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.portFlags.Selector == "" { cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } portMappings, err := parsePortMappings(args[0]) if err != nil { log.Fatalf("Error parsing port mappings: %s", err.Error()) } cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings) err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) { config := configutil.GetConfig(false) // Check if we should add to existing port mapping for _, v := range *config.DevSpace.PortForwarding { var selectors map[string]*string if v.LabelSelector != nil { selectors = *v.LabelSelector } else { selectors = map[string]*string{} } if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) { portMap := append(*v.PortMappings, portMappings...) v.PortMappings = &portMap return } } portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{ ResourceType: configutil.String(cmd.portFlags.ResourceType), LabelSelector: &labelSelectorMap, PortMappings: &portMappings, }) config.DevSpace.PortForwarding = &portMap } func
(map1 map[string]*string, map2 map[string]*string) bool { if len(map1) != len(map2) { return false } for k, v := range map1 { if *map2[k] != *v { return false } } return true } func parsePortMappings(portMappingsString string) ([]*v1.PortMapping, error) { portMappings := make([]*v1.PortMapping, 0, 1) portMappingsSplitted := strings.Split(portMappingsString, ",") for _, v := range portMappingsSplitted { portMapping := strings.Split(v, ":") if len(portMapping) != 1 && len(portMapping) != 2 { return nil, fmt.Errorf("Error parsing port mapping: %s", v) } portMappingStruct := &v1.PortMapping{} firstPort, err := strconv.Atoi(portMapping[0]) if err != nil { return nil, err } if len(portMapping) == 1 { portMappingStruct.LocalPort = &firstPort portMappingStruct.RemotePort = portMappingStruct.LocalPort } else { portMappingStruct.LocalPort = &firstPort secondPort, err := strconv.Atoi(portMapping[1]) if err != nil { return nil, err } portMappingStruct.RemotePort = &secondPort } portMappings = append(portMappings, portMappingStruct) } return portMappings, nil } func parseSelectors(selectorString string) (map[string]*string, error) { selectorMap := make(map[string]*string) if selectorString == "" { return selectorMap, nil } selectors := strings.Split(selectorString, ",") for _, v := range selectors { keyValue := strings.Split(v, "=") if len(keyValue) != 2 { return nil, fmt.Errorf("Wrong selector format: %s", selectorString) } selector := strings.TrimSpace(keyValue[1]) selectorMap[strings.TrimSpace(keyValue[0])] = &selector } return selectorMap, nil }
isMapEqual
identifier_name
add.go
package cmd import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "k8s.io/helm/pkg/repo" "github.com/covexo/devspace/pkg/util/stdinutil" "github.com/covexo/devspace/pkg/util/tar" "github.com/covexo/devspace/pkg/util/yamlutil" helmClient "github.com/covexo/devspace/pkg/devspace/clients/helm" "github.com/covexo/devspace/pkg/devspace/clients/kubectl" "github.com/covexo/devspace/pkg/devspace/config/configutil" "github.com/covexo/devspace/pkg/devspace/config/v1" "github.com/covexo/devspace/pkg/util/log" "github.com/russross/blackfriday" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" ) // AddCmd holds the information needed for the add command type AddCmd struct { flags *AddCmdFlags syncFlags *addSyncCmdFlags portFlags *addPortCmdFlags packageFlags *addPackageFlags dsConfig *v1.DevSpaceConfig } // AddCmdFlags holds the possible flags for the add command type AddCmdFlags struct { } type addSyncCmdFlags struct { ResourceType string Selector string LocalPath string ContainerPath string ExcludedPaths string } type addPortCmdFlags struct { ResourceType string Selector string } type addPackageFlags struct { AppVersion string ChartVersion string SkipQuestion bool } func init() { cmd := &AddCmd{ flags: &AddCmdFlags{}, syncFlags: &addSyncCmdFlags{}, portFlags: &addPortCmdFlags{}, packageFlags: &addPackageFlags{}, } addCmd := &cobra.Command{ Use: "add", Short: "Change the devspace configuration", Long: ` ####################################################### #################### devspace add ##################### ####################################################### You can change the following configuration with the add command: * Sync paths (sync) * Forwarded ports (port) ####################################################### `, Args: cobra.NoArgs, } rootCmd.AddCommand(addCmd) addSyncCmd := &cobra.Command{ Use: "sync", Short: "Add a sync path to the devspace", Long: ` ####################################################### ################# devspace add sync ################### ####################################################### Add a sync path to the devspace How to use: devspace add sync --local=app --container=/app ####################################################### `, Args: cobra.NoArgs, Run: cmd.RunAddSync, } addCmd.AddCommand(addSyncCmd) addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type") addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path") addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)") addSyncCmd.MarkFlagRequired("local") addSyncCmd.MarkFlagRequired("container") addPortCmd := &cobra.Command{ Use: "port", Short: "Add a new port forward configuration", Long: ` ####################################################### ################ devspace add port #################### ####################################################### Add a new port mapping that should be forwarded to the devspace (format is local:remote comma separated): devspace add port 8080:80,3000 ####################################################### `, Args: cobra.ExactArgs(1), Run: cmd.RunAddPort, } addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type") addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)") addCmd.AddCommand(addPortCmd) addPackageCmd := &cobra.Command{ Use: "package", Short: "Add a helm chart", Long: ` ####################################################### ############### devspace add package ################## ####################################################### Adds an existing helm chart to the devspace (run 'devspace add package' to display all available helm charts) Examples: devspace add package devspace add package mysql devspace add package mysql --app-version=5.7.14 devspace add package mysql --chart-version=0.10.3 ####################################################### `, Run: cmd.RunAddPackage, } addPackageCmd.Flags().StringVar(&cmd.packageFlags.AppVersion, "app-version", "", "App version") addPackageCmd.Flags().StringVar(&cmd.packageFlags.ChartVersion, "chart-version", "", "Chart version") addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser") addCmd.AddCommand(addPackageCmd) } // RunAddPackage executes the add package command logic func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) { kubectl, err := kubectl.NewClient() if err != nil { log.Fatalf("Unable to create new kubectl client: %v", err) } helm, err := helmClient.NewClient(kubectl, false) if err != nil { log.Fatalf("Error initializing helm client: %v", err) }
if len(args) != 1 { helm.PrintAllAvailableCharts() return } log.StartWait("Search Chart") repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion) log.StopWait() if err != nil { log.Fatal(err) } log.Done("Chart found") cwd, err := os.Getwd() if err != nil { log.Fatal(err) } requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml") _, err = os.Stat(requirementsFile) if os.IsNotExist(err) { entry := "dependencies:\n" + "- name: \"" + version.GetName() + "\"\n" + " version: \"" + version.GetVersion() + "\"\n" + " repository: \"" + repo.URL + "\"\n" err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600) if err != nil { log.Fatal(err) } } else { yamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", requirementsFile, err) } dependenciesArr := []interface{}{} if dependencies, ok := yamlContents["dependencies"]; ok { dependenciesArr, ok = dependencies.([]interface{}) if ok == false { log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile) } } dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{ "name": version.GetName(), "version": version.GetVersion(), "repository": repo.URL, }) yamlContents["dependencies"] = dependenciesArr err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile) if err != nil { log.Fatal(err) } } log.StartWait("Update chart dependencies") err = helm.UpdateDependencies(filepath.Join(cwd, "chart")) log.StopWait() if err != nil { log.Fatal(err) } // Check if key already exists valuesYaml := filepath.Join(cwd, "chart", "values.yaml") valuesYamlContents := map[interface{}]interface{}{} err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents) if err != nil { log.Fatalf("Error parsing %s: %v", valuesYaml, err) } if _, ok := valuesYamlContents[version.GetName()]; ok == false { f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil { log.Fatal(err) } } log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName()) cmd.showReadme(version) } func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) { cwd, err := os.Getwd() if err != nil { log.Fatal(err) } if cmd.packageFlags.SkipQuestion { return } showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{ Question: "Do you want to open the package README? (y|n)", DefaultValue: "y", ValidationRegexPattern: "^(y|n)", }) if showReadme == "n" { return } content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md") if err != nil { log.Fatal(err) } output := blackfriday.MarkdownCommon([]byte(content)) f, err := os.OpenFile(filepath.Join(os.TempDir(), "Readme.html"), os.O_RDWR|os.O_CREATE, 0600) if err != nil { log.Fatal(err) } defer f.Close() _, err = f.Write(output) if err != nil { log.Fatal(err) } f.Close() open.Start(f.Name()) } // RunAddSync executes the add sync command logic func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.syncFlags.Selector == "" { cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } excludedPaths := make([]string, 0, 0) if cmd.syncFlags.ExcludedPaths != "" { excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",") for _, v := range excludedPathStrings { excludedPath := strings.TrimSpace(v) excludedPaths = append(excludedPaths, excludedPath) } } workdir, err := os.Getwd() if err != nil { log.Fatalf("Unable to determine current workdir: %s", err.Error()) } cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir) cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./") if cmd.syncFlags.ContainerPath[0] != '/' { log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.") } syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{ ResourceType: configutil.String(cmd.syncFlags.ResourceType), LabelSelector: &labelSelectorMap, ContainerPath: configutil.String(cmd.syncFlags.ContainerPath), LocalSubPath: configutil.String(cmd.syncFlags.LocalPath), ExcludePaths: &excludedPaths, }) config.DevSpace.Sync = &syncConfig err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } // RunAddPort executes the add port command logic func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) { config := configutil.GetConfig(false) if cmd.portFlags.Selector == "" { cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name } labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector) if err != nil { log.Fatalf("Error parsing selectors: %s", err.Error()) } portMappings, err := parsePortMappings(args[0]) if err != nil { log.Fatalf("Error parsing port mappings: %s", err.Error()) } cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings) err = configutil.SaveConfig() if err != nil { log.Fatalf("Couldn't save config file: %s", err.Error()) } } func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) { config := configutil.GetConfig(false) // Check if we should add to existing port mapping for _, v := range *config.DevSpace.PortForwarding { var selectors map[string]*string if v.LabelSelector != nil { selectors = *v.LabelSelector } else { selectors = map[string]*string{} } if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) { portMap := append(*v.PortMappings, portMappings...) v.PortMappings = &portMap return } } portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{ ResourceType: configutil.String(cmd.portFlags.ResourceType), LabelSelector: &labelSelectorMap, PortMappings: &portMappings, }) config.DevSpace.PortForwarding = &portMap } func isMapEqual(map1 map[string]*string, map2 map[string]*string) bool { if len(map1) != len(map2) { return false } for k, v := range map1 { if *map2[k] != *v { return false } } return true } func parsePortMappings(portMappingsString string) ([]*v1.PortMapping, error) { portMappings := make([]*v1.PortMapping, 0, 1) portMappingsSplitted := strings.Split(portMappingsString, ",") for _, v := range portMappingsSplitted { portMapping := strings.Split(v, ":") if len(portMapping) != 1 && len(portMapping) != 2 { return nil, fmt.Errorf("Error parsing port mapping: %s", v) } portMappingStruct := &v1.PortMapping{} firstPort, err := strconv.Atoi(portMapping[0]) if err != nil { return nil, err } if len(portMapping) == 1 { portMappingStruct.LocalPort = &firstPort portMappingStruct.RemotePort = portMappingStruct.LocalPort } else { portMappingStruct.LocalPort = &firstPort secondPort, err := strconv.Atoi(portMapping[1]) if err != nil { return nil, err } portMappingStruct.RemotePort = &secondPort } portMappings = append(portMappings, portMappingStruct) } return portMappings, nil } func parseSelectors(selectorString string) (map[string]*string, error) { selectorMap := make(map[string]*string) if selectorString == "" { return selectorMap, nil } selectors := strings.Split(selectorString, ",") for _, v := range selectors { keyValue := strings.Split(v, "=") if len(keyValue) != 2 { return nil, fmt.Errorf("Wrong selector format: %s", selectorString) } selector := strings.TrimSpace(keyValue[1]) selectorMap[strings.TrimSpace(keyValue[0])] = &selector } return selectorMap, nil }
random_line_split
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::default() /// .protocol(Protocol::EIP) /// .gateway("192.168.1.120") /// .plc(PlcKind::ControlLogix) /// .name("MyTag1") /// .element_size(16) /// .element_count(1) /// .path("1,0") /// .read_cache_ms(0) /// .build() /// .unwrap(); /// let tag = RawTag::new(path, timeout).unwrap(); /// let status = tag.status(); /// assert!(status.is_ok()); /// } /// /// ``` #[derive(Default, Debug)] pub struct PathBuilder { protocol: Option<Protocol>, debug: Option<DebugLevel>, elem_count: Option<usize>, elem_size: Option<usize>, read_cache_ms: Option<usize>, plc: Option<PlcKind>, name: Option<String>, path: Option<String>, gateway: Option<String>, use_connected_msg: Option<bool>, } impl PathBuilder { /// generic attribute. /// defining the current debugging level. /// please use [`plc::set_debug_level`](../plc/fn.set_debug_level.html) instead. #[deprecated] #[inline] pub fn debug(&mut self, level: DebugLevel) -> &mut Self
/// generic attribute. /// Required. Determines the type of the PLC protocol. #[inline] pub fn protocol(&mut self, protocol: Protocol) -> &mut Self { self.protocol = Some(protocol); self } /// generic attribute. /// Optional. All tags are treated as arrays. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1) #[inline] pub fn element_count(&mut self, count: usize) -> &mut Self { self.elem_count = Some(count); self } /// generic attribute /// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible #[inline] pub fn element_size(&mut self, size: usize) -> &mut Self { self.elem_size = Some(size); self } /// generic attribute: /// Optional. An integer number of milliseconds to cache read data. /// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds. #[inline] pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self { self.read_cache_ms = Some(millis); self } /// Required for EIP. Determines the type of the PLC #[inline] pub fn plc(&mut self, plc: PlcKind) -> &mut Self { self.plc = Some(plc); self } /// - EIP /// IP address or host name. /// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote). /// - ModBus /// Required IP address or host name and optional port /// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port. #[inline] pub fn gateway(&mut self, gateway: impl AsRef<str>) -> &mut Self { self.gateway = Some(gateway.as_ref().to_owned()); self } /// - EIP /// This is the full name of the tag. For program tags, prepend Program:<program name>. where <program name> is the name of the program in which the tag is created /// - ModBus /// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero). /// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000. /// /// you might want to use `register()` instead of `name()` for Modbus #[inline] pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self { self.name = Some(name.as_ref().to_owned()); self } /// set register for Modbus pub fn register(&mut self, reg: Register) -> &mut Self { self.name = Some(format!("{}", reg)); self } /// - EIP /// AB: CIP path to PLC CPU. I.e. 1,0. /// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute. /// - ModBus /// Required The server/unit ID. Must be an integer value between 0 and 255. /// Servers may support more than one unit or may bridge to other units. #[inline] pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self { self.path = Some(path.as_ref().to_owned()); self } /// EIP only /// Optional 1 = use CIP connection, 0 = use UCMM. /// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this. #[inline] pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self { self.use_connected_msg = Some(yes); self } /// check required attributes or conflict attributes fn check(&self) -> Result<()> { //check protocol, required if self.protocol.is_none() { return Err(anyhow!("protocol required")); } let protocol = self.protocol.unwrap(); // check required attributes match protocol { Protocol::EIP => { //TODO: check gateway, either ip or host name //check plc, required if self.plc.is_none() { return Err(anyhow!("plc required")); } let plc = self.plc.unwrap(); if plc == PlcKind::ControlLogix { if self.path.is_none() { return Err(anyhow!("path required for controllogix")); } return Ok(()); //skip check for elem_size } else if plc == PlcKind::Micro800 { if self.path.is_some() { return Err(anyhow!("path must not provided for micro800")); } } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } Protocol::ModBus => { //TODO: check gateway, host with port if self.gateway.is_none() { return Err(anyhow!("gateway required")); } if self.name.is_none() { return Err(anyhow!("name required")); } //path is number [0-255] match self.path { Some(ref path) => { let _: u8 = path .parse() .or(Err(anyhow!("path is a number in range [0-255]")))?; } None => return Err(anyhow!("path required")), } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } } Ok(()) } /// build full tag path pub fn build(&self) -> Result<String> { self.check()?; let mut path_buf = vec![]; let protocol = self.protocol.unwrap(); path_buf.push(format!("protocol={}", protocol)); match protocol { Protocol::EIP => { if let Some(plc) = self.plc { path_buf.push(format!("plc={}", plc)); } if let Some(yes) = self.use_connected_msg { path_buf.push(format!("use_connected_msg={}", yes as u8)); } } Protocol::ModBus => {} } if let Some(ref gateway) = self.gateway { path_buf.push(format!("gateway={}", gateway)); } if let Some(ref path) = self.path { path_buf.push(format!("path={}", path)); } if let Some(ref name) = self.name { path_buf.push(format!("name={}", name)); } if let Some(elem_count) = self.elem_count { path_buf.push(format!("elem_count={}", elem_count)); } if let Some(elem_size) = self.elem_size { path_buf.push(format!("elem_size={}", elem_size)); } if let Some(read_cache_ms) = self.read_cache_ms { path_buf.push(format!("read_cache_ms={}", read_cache_ms)); } if let Some(debug) = self.debug { let level: u8 = debug.into(); path_buf.push(format!("debug={}", level)); } let buf = path_buf.join("&"); Ok(buf.to_owned()) } } /// library supported protocols #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Protocol { /// EIP protocol EIP, /// Modbus protocol ModBus, } impl fmt::Display for Protocol { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Protocol::EIP => write!(f, "ab-eip"), Protocol::ModBus => write!(f, "modbus-tcp"), } } } ///modbus supported register pub enum Register { ///coil registers Coil(u16), ///discrete inputs Discrete(u16), ///holding registers Holding(u16), ///input registers Input(u16), } impl fmt::Display for Register { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Register::Coil(v) => write!(f, "co{}", v), Register::Discrete(v) => write!(f, "di{}", v), Register::Holding(v) => write!(f, "hr{}", v), Register::Input(v) => write!(f, "ir{}", v), } } } /// plc kind, required for EIP protocol #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum PlcKind { /// Tell the library that this tag is in a Control Logix-class PLC ControlLogix, /// Tell the library that this tag is in a PLC/5 PLC PLC5, /// Tell the library that this tag is in a SLC 500 PLC SLC500, /// Tell the library that this tag is in a Control Logix-class PLC using the PLC/5 protocol LogixPCCC, /// Tell the library that this tag is in a Micro800-class PLC Micro800, /// Tell the library that this tag is in a Micrologix PLC MicroLogix, } impl fmt::Display for PlcKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PlcKind::ControlLogix => write!(f, "controllogix"), PlcKind::PLC5 => write!(f, "plc5"), PlcKind::SLC500 => write!(f, "slc500"), PlcKind::LogixPCCC => write!(f, "logixpccc"), PlcKind::Micro800 => write!(f, "micro800"), PlcKind::MicroLogix => write!(f, "micrologix"), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_eip_builder() { let path = PathBuilder::default() .protocol(Protocol::EIP) .gateway("192.168.1.120") .plc(PlcKind::ControlLogix) .name("MyTag1") .element_size(16) .element_count(1) .path("1,0") .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=ab-eip&plc=controllogix&gateway=192.168.1.120&path=1,0&name=MyTag1&elem_count=1&elem_size=16&read_cache_ms=0"); } #[test] fn test_modbus_builder() { let path = PathBuilder::default() .protocol(Protocol::ModBus) .gateway("192.168.1.120:502") .path("0") .register(Register::Coil(42)) .element_size(16) .element_count(1) .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=modbus-tcp&gateway=192.168.1.120:502&path=0&name=co42&elem_count=1&elem_size=16&read_cache_ms=0"); } }
{ self.debug = Some(level); self }
identifier_body
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::default() /// .protocol(Protocol::EIP) /// .gateway("192.168.1.120") /// .plc(PlcKind::ControlLogix) /// .name("MyTag1") /// .element_size(16) /// .element_count(1) /// .path("1,0") /// .read_cache_ms(0) /// .build() /// .unwrap(); /// let tag = RawTag::new(path, timeout).unwrap(); /// let status = tag.status(); /// assert!(status.is_ok()); /// } /// /// ``` #[derive(Default, Debug)] pub struct PathBuilder { protocol: Option<Protocol>, debug: Option<DebugLevel>, elem_count: Option<usize>, elem_size: Option<usize>, read_cache_ms: Option<usize>, plc: Option<PlcKind>, name: Option<String>, path: Option<String>, gateway: Option<String>, use_connected_msg: Option<bool>, } impl PathBuilder { /// generic attribute. /// defining the current debugging level. /// please use [`plc::set_debug_level`](../plc/fn.set_debug_level.html) instead. #[deprecated] #[inline] pub fn debug(&mut self, level: DebugLevel) -> &mut Self { self.debug = Some(level); self } /// generic attribute. /// Required. Determines the type of the PLC protocol. #[inline] pub fn protocol(&mut self, protocol: Protocol) -> &mut Self { self.protocol = Some(protocol); self } /// generic attribute. /// Optional. All tags are treated as arrays. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1) #[inline] pub fn element_count(&mut self, count: usize) -> &mut Self { self.elem_count = Some(count); self } /// generic attribute /// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible #[inline] pub fn element_size(&mut self, size: usize) -> &mut Self { self.elem_size = Some(size); self } /// generic attribute: /// Optional. An integer number of milliseconds to cache read data. /// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds. #[inline] pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self { self.read_cache_ms = Some(millis); self } /// Required for EIP. Determines the type of the PLC #[inline] pub fn plc(&mut self, plc: PlcKind) -> &mut Self { self.plc = Some(plc); self } /// - EIP /// IP address or host name. /// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote). /// - ModBus /// Required IP address or host name and optional port /// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port. #[inline] pub fn
(&mut self, gateway: impl AsRef<str>) -> &mut Self { self.gateway = Some(gateway.as_ref().to_owned()); self } /// - EIP /// This is the full name of the tag. For program tags, prepend Program:<program name>. where <program name> is the name of the program in which the tag is created /// - ModBus /// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero). /// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000. /// /// you might want to use `register()` instead of `name()` for Modbus #[inline] pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self { self.name = Some(name.as_ref().to_owned()); self } /// set register for Modbus pub fn register(&mut self, reg: Register) -> &mut Self { self.name = Some(format!("{}", reg)); self } /// - EIP /// AB: CIP path to PLC CPU. I.e. 1,0. /// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute. /// - ModBus /// Required The server/unit ID. Must be an integer value between 0 and 255. /// Servers may support more than one unit or may bridge to other units. #[inline] pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self { self.path = Some(path.as_ref().to_owned()); self } /// EIP only /// Optional 1 = use CIP connection, 0 = use UCMM. /// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this. #[inline] pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self { self.use_connected_msg = Some(yes); self } /// check required attributes or conflict attributes fn check(&self) -> Result<()> { //check protocol, required if self.protocol.is_none() { return Err(anyhow!("protocol required")); } let protocol = self.protocol.unwrap(); // check required attributes match protocol { Protocol::EIP => { //TODO: check gateway, either ip or host name //check plc, required if self.plc.is_none() { return Err(anyhow!("plc required")); } let plc = self.plc.unwrap(); if plc == PlcKind::ControlLogix { if self.path.is_none() { return Err(anyhow!("path required for controllogix")); } return Ok(()); //skip check for elem_size } else if plc == PlcKind::Micro800 { if self.path.is_some() { return Err(anyhow!("path must not provided for micro800")); } } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } Protocol::ModBus => { //TODO: check gateway, host with port if self.gateway.is_none() { return Err(anyhow!("gateway required")); } if self.name.is_none() { return Err(anyhow!("name required")); } //path is number [0-255] match self.path { Some(ref path) => { let _: u8 = path .parse() .or(Err(anyhow!("path is a number in range [0-255]")))?; } None => return Err(anyhow!("path required")), } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } } Ok(()) } /// build full tag path pub fn build(&self) -> Result<String> { self.check()?; let mut path_buf = vec![]; let protocol = self.protocol.unwrap(); path_buf.push(format!("protocol={}", protocol)); match protocol { Protocol::EIP => { if let Some(plc) = self.plc { path_buf.push(format!("plc={}", plc)); } if let Some(yes) = self.use_connected_msg { path_buf.push(format!("use_connected_msg={}", yes as u8)); } } Protocol::ModBus => {} } if let Some(ref gateway) = self.gateway { path_buf.push(format!("gateway={}", gateway)); } if let Some(ref path) = self.path { path_buf.push(format!("path={}", path)); } if let Some(ref name) = self.name { path_buf.push(format!("name={}", name)); } if let Some(elem_count) = self.elem_count { path_buf.push(format!("elem_count={}", elem_count)); } if let Some(elem_size) = self.elem_size { path_buf.push(format!("elem_size={}", elem_size)); } if let Some(read_cache_ms) = self.read_cache_ms { path_buf.push(format!("read_cache_ms={}", read_cache_ms)); } if let Some(debug) = self.debug { let level: u8 = debug.into(); path_buf.push(format!("debug={}", level)); } let buf = path_buf.join("&"); Ok(buf.to_owned()) } } /// library supported protocols #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Protocol { /// EIP protocol EIP, /// Modbus protocol ModBus, } impl fmt::Display for Protocol { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Protocol::EIP => write!(f, "ab-eip"), Protocol::ModBus => write!(f, "modbus-tcp"), } } } ///modbus supported register pub enum Register { ///coil registers Coil(u16), ///discrete inputs Discrete(u16), ///holding registers Holding(u16), ///input registers Input(u16), } impl fmt::Display for Register { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Register::Coil(v) => write!(f, "co{}", v), Register::Discrete(v) => write!(f, "di{}", v), Register::Holding(v) => write!(f, "hr{}", v), Register::Input(v) => write!(f, "ir{}", v), } } } /// plc kind, required for EIP protocol #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum PlcKind { /// Tell the library that this tag is in a Control Logix-class PLC ControlLogix, /// Tell the library that this tag is in a PLC/5 PLC PLC5, /// Tell the library that this tag is in a SLC 500 PLC SLC500, /// Tell the library that this tag is in a Control Logix-class PLC using the PLC/5 protocol LogixPCCC, /// Tell the library that this tag is in a Micro800-class PLC Micro800, /// Tell the library that this tag is in a Micrologix PLC MicroLogix, } impl fmt::Display for PlcKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PlcKind::ControlLogix => write!(f, "controllogix"), PlcKind::PLC5 => write!(f, "plc5"), PlcKind::SLC500 => write!(f, "slc500"), PlcKind::LogixPCCC => write!(f, "logixpccc"), PlcKind::Micro800 => write!(f, "micro800"), PlcKind::MicroLogix => write!(f, "micrologix"), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_eip_builder() { let path = PathBuilder::default() .protocol(Protocol::EIP) .gateway("192.168.1.120") .plc(PlcKind::ControlLogix) .name("MyTag1") .element_size(16) .element_count(1) .path("1,0") .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=ab-eip&plc=controllogix&gateway=192.168.1.120&path=1,0&name=MyTag1&elem_count=1&elem_size=16&read_cache_ms=0"); } #[test] fn test_modbus_builder() { let path = PathBuilder::default() .protocol(Protocol::ModBus) .gateway("192.168.1.120:502") .path("0") .register(Register::Coil(42)) .element_size(16) .element_count(1) .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=modbus-tcp&gateway=192.168.1.120:502&path=0&name=co42&elem_count=1&elem_size=16&read_cache_ms=0"); } }
gateway
identifier_name
builder.rs
//! builders for tag path and tag use crate::DebugLevel; use std::fmt; pub use anyhow::Result; /// builder to build tag full path /// /// # Examples /// ```rust,ignore /// use plctag::builder::*; /// use plctag::RawTag; /// /// fn main() { /// let timeout = 100; /// let path = PathBuilder::default() /// .protocol(Protocol::EIP) /// .gateway("192.168.1.120") /// .plc(PlcKind::ControlLogix) /// .name("MyTag1") /// .element_size(16) /// .element_count(1) /// .path("1,0") /// .read_cache_ms(0) /// .build() /// .unwrap(); /// let tag = RawTag::new(path, timeout).unwrap(); /// let status = tag.status(); /// assert!(status.is_ok()); /// } /// /// ``` #[derive(Default, Debug)] pub struct PathBuilder { protocol: Option<Protocol>, debug: Option<DebugLevel>, elem_count: Option<usize>, elem_size: Option<usize>, read_cache_ms: Option<usize>, plc: Option<PlcKind>, name: Option<String>, path: Option<String>, gateway: Option<String>, use_connected_msg: Option<bool>, } impl PathBuilder { /// generic attribute. /// defining the current debugging level. /// please use [`plc::set_debug_level`](../plc/fn.set_debug_level.html) instead. #[deprecated] #[inline] pub fn debug(&mut self, level: DebugLevel) -> &mut Self { self.debug = Some(level); self } /// generic attribute. /// Required. Determines the type of the PLC protocol. #[inline] pub fn protocol(&mut self, protocol: Protocol) -> &mut Self { self.protocol = Some(protocol); self } /// generic attribute. /// Optional. All tags are treated as arrays. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1) #[inline] pub fn element_count(&mut self, count: usize) -> &mut Self { self.elem_count = Some(count); self } /// generic attribute /// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible #[inline] pub fn element_size(&mut self, size: usize) -> &mut Self { self.elem_size = Some(size); self } /// generic attribute: /// Optional. An integer number of milliseconds to cache read data. /// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds. #[inline] pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self { self.read_cache_ms = Some(millis); self } /// Required for EIP. Determines the type of the PLC #[inline] pub fn plc(&mut self, plc: PlcKind) -> &mut Self { self.plc = Some(plc); self } /// - EIP /// IP address or host name. /// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote). /// - ModBus /// Required IP address or host name and optional port /// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port. #[inline] pub fn gateway(&mut self, gateway: impl AsRef<str>) -> &mut Self { self.gateway = Some(gateway.as_ref().to_owned()); self } /// - EIP /// This is the full name of the tag. For program tags, prepend Program:<program name>. where <program name> is the name of the program in which the tag is created /// - ModBus /// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero). /// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000. /// /// you might want to use `register()` instead of `name()` for Modbus #[inline] pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self { self.name = Some(name.as_ref().to_owned()); self } /// set register for Modbus pub fn register(&mut self, reg: Register) -> &mut Self { self.name = Some(format!("{}", reg)); self } /// - EIP /// AB: CIP path to PLC CPU. I.e. 1,0. /// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute. /// - ModBus /// Required The server/unit ID. Must be an integer value between 0 and 255. /// Servers may support more than one unit or may bridge to other units. #[inline] pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self { self.path = Some(path.as_ref().to_owned()); self } /// EIP only /// Optional 1 = use CIP connection, 0 = use UCMM. /// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this. #[inline] pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self { self.use_connected_msg = Some(yes); self } /// check required attributes or conflict attributes fn check(&self) -> Result<()> { //check protocol, required if self.protocol.is_none() { return Err(anyhow!("protocol required")); } let protocol = self.protocol.unwrap(); // check required attributes match protocol { Protocol::EIP => { //TODO: check gateway, either ip or host name //check plc, required if self.plc.is_none() { return Err(anyhow!("plc required")); } let plc = self.plc.unwrap(); if plc == PlcKind::ControlLogix { if self.path.is_none() { return Err(anyhow!("path required for controllogix")); } return Ok(()); //skip check for elem_size } else if plc == PlcKind::Micro800 { if self.path.is_some() { return Err(anyhow!("path must not provided for micro800")); } } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } Protocol::ModBus => { //TODO: check gateway, host with port if self.gateway.is_none() { return Err(anyhow!("gateway required")); } if self.name.is_none() { return Err(anyhow!("name required")); } //path is number [0-255] match self.path { Some(ref path) => { let _: u8 = path .parse() .or(Err(anyhow!("path is a number in range [0-255]")))?; } None => return Err(anyhow!("path required")), } if self.elem_size.is_none() { return Err(anyhow!("element size required")); } } } Ok(()) } /// build full tag path pub fn build(&self) -> Result<String> { self.check()?; let mut path_buf = vec![]; let protocol = self.protocol.unwrap(); path_buf.push(format!("protocol={}", protocol)); match protocol { Protocol::EIP => { if let Some(plc) = self.plc { path_buf.push(format!("plc={}", plc));
} if let Some(yes) = self.use_connected_msg { path_buf.push(format!("use_connected_msg={}", yes as u8)); } } Protocol::ModBus => {} } if let Some(ref gateway) = self.gateway { path_buf.push(format!("gateway={}", gateway)); } if let Some(ref path) = self.path { path_buf.push(format!("path={}", path)); } if let Some(ref name) = self.name { path_buf.push(format!("name={}", name)); } if let Some(elem_count) = self.elem_count { path_buf.push(format!("elem_count={}", elem_count)); } if let Some(elem_size) = self.elem_size { path_buf.push(format!("elem_size={}", elem_size)); } if let Some(read_cache_ms) = self.read_cache_ms { path_buf.push(format!("read_cache_ms={}", read_cache_ms)); } if let Some(debug) = self.debug { let level: u8 = debug.into(); path_buf.push(format!("debug={}", level)); } let buf = path_buf.join("&"); Ok(buf.to_owned()) } } /// library supported protocols #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Protocol { /// EIP protocol EIP, /// Modbus protocol ModBus, } impl fmt::Display for Protocol { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Protocol::EIP => write!(f, "ab-eip"), Protocol::ModBus => write!(f, "modbus-tcp"), } } } ///modbus supported register pub enum Register { ///coil registers Coil(u16), ///discrete inputs Discrete(u16), ///holding registers Holding(u16), ///input registers Input(u16), } impl fmt::Display for Register { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Register::Coil(v) => write!(f, "co{}", v), Register::Discrete(v) => write!(f, "di{}", v), Register::Holding(v) => write!(f, "hr{}", v), Register::Input(v) => write!(f, "ir{}", v), } } } /// plc kind, required for EIP protocol #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum PlcKind { /// Tell the library that this tag is in a Control Logix-class PLC ControlLogix, /// Tell the library that this tag is in a PLC/5 PLC PLC5, /// Tell the library that this tag is in a SLC 500 PLC SLC500, /// Tell the library that this tag is in a Control Logix-class PLC using the PLC/5 protocol LogixPCCC, /// Tell the library that this tag is in a Micro800-class PLC Micro800, /// Tell the library that this tag is in a Micrologix PLC MicroLogix, } impl fmt::Display for PlcKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PlcKind::ControlLogix => write!(f, "controllogix"), PlcKind::PLC5 => write!(f, "plc5"), PlcKind::SLC500 => write!(f, "slc500"), PlcKind::LogixPCCC => write!(f, "logixpccc"), PlcKind::Micro800 => write!(f, "micro800"), PlcKind::MicroLogix => write!(f, "micrologix"), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_eip_builder() { let path = PathBuilder::default() .protocol(Protocol::EIP) .gateway("192.168.1.120") .plc(PlcKind::ControlLogix) .name("MyTag1") .element_size(16) .element_count(1) .path("1,0") .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=ab-eip&plc=controllogix&gateway=192.168.1.120&path=1,0&name=MyTag1&elem_count=1&elem_size=16&read_cache_ms=0"); } #[test] fn test_modbus_builder() { let path = PathBuilder::default() .protocol(Protocol::ModBus) .gateway("192.168.1.120:502") .path("0") .register(Register::Coil(42)) .element_size(16) .element_count(1) .read_cache_ms(0) .build() .unwrap(); assert_eq!(path, "protocol=modbus-tcp&gateway=192.168.1.120:502&path=0&name=co42&elem_count=1&elem_size=16&read_cache_ms=0"); } }
random_line_split
protocol.go
// Copyright 2009 Joubin Houshyar // // 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. // /* */ package redis import ( "os" "io" "bufio" "strconv" "bytes" "log" // "fmt" ) // ---------------------------------------------------------------------------- // Wire // ---------------------------------------------------------------------------- // protocol's special bytes const ( CR_BYTE byte = byte('\r') LF_BYTE = byte('\n') SPACE_BYTE = byte(' ') ERR_BYTE = byte(45) OK_BYTE = byte(43) COUNT_BYTE = byte(42) SIZE_BYTE = byte(36) NUM_BYTE = byte(58) FALSE_BYTE = byte(48) TRUE_BYTE = byte(49) ) type ctlbytes []byte var CRLF ctlbytes = ctlbytes{CR_BYTE, LF_BYTE} var WHITESPACE ctlbytes = ctlbytes{SPACE_BYTE} // ---------------------------------------------------------------------------- // Services // ---------------------------------------------------------------------------- // Creates the byte buffer that corresponds to the specified Command and // provided command arguments. // // TODO: tedious but need to check for errors on all buffer writes .. // func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error)
// Creates a specific Future type for the given Redis command // and returns it as a generic reference. // func CreateFuture(cmd *Command) (future interface{}) { switch cmd.RespType { case BOOLEAN: future = newFutureBool() case BULK: future = newFutureBytes() case MULTI_BULK: future = newFutureBytesArray() case NUMBER: future = newFutureInt64() case STATUS: // future = newFutureString(); future = newFutureBool() case STRING: future = newFutureString() // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } return } // Sets the type specific result value from the response for the future reference // based on the command type. // func SetFutureResult(future interface{}, cmd *Command, r Response) { if r.IsError() { future.(FutureResult).onError(NewRedisError(r.GetMessage())) } else { switch cmd.RespType { case BOOLEAN: future.(FutureBool).set(r.GetBooleanValue()) case BULK: future.(FutureBytes).set(r.GetBulkData()) case MULTI_BULK: future.(FutureBytesArray).set(r.GetMultiBulkData()) case NUMBER: future.(FutureInt64).set(r.GetNumberValue()) case STATUS: // future.(FutureString).set(r.GetMessage()); future.(FutureBool).set(true) case STRING: future.(FutureString).set(r.GetStringValue()) // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } } } // Gets the response to the command. // Any errors (whether runtime or bugs) are returned as os.Error. // The returned response (regardless of flavor) may have (application level) // errors as sent from Redis server. // func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) { switch cmd.RespType { case BOOLEAN: resp, err = getBooleanResponse(reader, cmd) case BULK: resp, err = getBulkResponse(reader, cmd) case MULTI_BULK: resp, err = getMultiBulkResponse(reader, cmd) case NUMBER: resp, err = getNumberResponse(reader, cmd) case STATUS: resp, err = getStatusResponse(reader, cmd) case STRING: resp, err = getStringResponse(reader, cmd) // case VIRTUAL: // resp, err = getVirtualResponse (); } return } // ---------------------------------------------------------------------------- // internal ops // ---------------------------------------------------------------------------- func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { // fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code); buff, error, fault := readLine(conn) if fault == nil { line := bytes.NewBuffer(buff).String() // fmt.Printf("getStatusResponse: %s\n", line); resp = newStatusResponse(line, error) } return resp, fault } func getBooleanResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { b := buff[1] == TRUE_BYTE resp = newBooleanResponse(b, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] str := bytes.NewBuffer(buff).String() resp = newStringResponse(str, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] numrep := bytes.NewBuffer(buff).String() num, err := strconv.Atoi64(numrep) if err == nil { resp = newNumberResponse(num, error) } else { e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String()) } } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func btoi64(buff []byte) (num int64, e os.Error) { numrep := bytes.NewBuffer(buff).String() num, e = strconv.Atoi64(numrep) if e != nil { e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String()) } return } func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } // log.Println("bulk data size: ", num); if num < 0 { return newBulkResponse(nil, false), nil } bulkdata, e3 := readBulkData(conn, num) if e3 != nil { return nil, e3 } return newBulkResponse(bulkdata, false), nil } func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != COUNT_BYTE { return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } log.Println("multibulk data count: ", num) if num < 0 { return newMultiBulkResponse(nil, false), nil } multibulkdata := make([][]byte, num) for i := int64(0); i < num; i++ { sbuf, e := readToCRLF(conn) if e != nil { return nil, e } if sbuf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE for data item in getMultiBulkResponse") } size, e2 := btoi64(sbuf[1:len(sbuf)]) if e2 != nil { return nil, e2 } // log.Println("item: bulk data size: ", size); if size < 0 { multibulkdata[i] = nil } else { bulkdata, e3 := readBulkData(conn, size) if e3 != nil { return nil, e3 } multibulkdata[i] = bulkdata } } return newMultiBulkResponse(multibulkdata, false), nil } // ---------------------------------------------------------------------------- // Response // ---------------------------------------------------------------------------- type Response interface { IsError() bool GetMessage() string GetBooleanValue() bool GetNumberValue() int64 GetStringValue() string GetBulkData() []byte GetMultiBulkData() [][]byte } type _response struct { isError bool msg string boolval bool numval int64 stringval string bulkdata []byte multibulkdata [][]byte } func (r *_response) IsError() bool { return r.isError } func (r *_response) GetMessage() string { return r.msg } func (r *_response) GetBooleanValue() bool { return r.boolval } func (r *_response) GetNumberValue() int64 { return r.numval } func (r *_response) GetStringValue() string { return r.stringval } func (r *_response) GetBulkData() []byte { return r.bulkdata } func (r *_response) GetMultiBulkData() [][]byte { return r.multibulkdata } func newAndInitResponse(isError bool) (r *_response) { r = new(_response) r.isError = isError r.bulkdata = nil r.multibulkdata = nil return } func newStatusResponse(msg string, isError bool) Response { r := newAndInitResponse(isError) r.msg = msg return r } func newBooleanResponse(val bool, isError bool) Response { r := newAndInitResponse(isError) r.boolval = val return r } func newNumberResponse(val int64, isError bool) Response { r := newAndInitResponse(isError) r.numval = val return r } func newStringResponse(val string, isError bool) Response { r := newAndInitResponse(isError) r.stringval = val return r } func newBulkResponse(val []byte, isError bool) Response { r := newAndInitResponse(isError) r.bulkdata = val return r } func newMultiBulkResponse(val [][]byte, isError bool) Response { r := newAndInitResponse(isError) r.multibulkdata = val return r } // ---------------------------------------------------------------------------- // Protocol i/o // ---------------------------------------------------------------------------- // reads all bytes upto CR-LF. (Will eat those last two bytes) // return the line []byte up to CR-LF // error returned is NOT ("-ERR ..."). If there is a Redis error // that is in the line buffer returned func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) { // reader := bufio.NewReader(conn); var buf []byte buf, err = reader.ReadBytes(CR_BYTE) if err == nil { var b byte b, err = reader.ReadByte() if err != nil { return } if b != LF_BYTE { err = os.NewError("<BUG> Expecting a Linefeed byte here!") } // log.Println("readToCRLF: ", buf); buffer = buf[0 : len(buf)-1] } return } func readLine(conn *bufio.Reader) (buf []byte, error bool, fault os.Error) { buf, fault = readToCRLF(conn) if fault == nil { error = buf[0] == ERR_BYTE } return } func readBulkData(conn *bufio.Reader, len int64) ([]byte, os.Error) { buff := make([]byte, len) _, e := io.ReadFull(conn, buff) if e != nil { return nil, NewErrorWithCause(SYSTEM_ERR, "Error while attempting read of bulkdata", e) } // fmt.Println ("Read ", n, " bytes. data: ", buff); crb, e1 := conn.ReadByte() if e1 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal CR:" + e1.String()) } if crb != CR_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not CR as expected") } lfb, e2 := conn.ReadByte() if e2 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal LF:" + e2.String()) } if lfb != LF_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not LF as expected.") } return buff, nil } // convenience func for now // but slated to optimize converting ints to their []byte literal representation func writeNum(b *bytes.Buffer, n int) (*bytes.Buffer, os.Error) { nb := ([]byte (strconv.Itoa(n))) b.Write(nb) return b, nil }
{ cmd_bytes := []byte(cmd.Code) buffer := bytes.NewBufferString("") buffer.WriteByte (COUNT_BYTE); buffer.Write ([]byte (strconv.Itoa(len(args)+1))) buffer.Write (CRLF); buffer.WriteByte (SIZE_BYTE); buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes)))) buffer.Write (CRLF); buffer.Write (cmd_bytes); buffer.Write (CRLF); for _, s := range args { buffer.WriteByte (SIZE_BYTE); buffer.Write([]byte(strconv.Itoa(len(s)))) buffer.Write(CRLF); buffer.Write(s); buffer.Write(CRLF); } return buffer.Bytes(), nil }
identifier_body
protocol.go
// Copyright 2009 Joubin Houshyar // // 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. // /* */ package redis import ( "os" "io" "bufio" "strconv" "bytes" "log" // "fmt" ) // ---------------------------------------------------------------------------- // Wire // ---------------------------------------------------------------------------- // protocol's special bytes const ( CR_BYTE byte = byte('\r') LF_BYTE = byte('\n') SPACE_BYTE = byte(' ') ERR_BYTE = byte(45) OK_BYTE = byte(43) COUNT_BYTE = byte(42) SIZE_BYTE = byte(36) NUM_BYTE = byte(58) FALSE_BYTE = byte(48) TRUE_BYTE = byte(49) ) type ctlbytes []byte var CRLF ctlbytes = ctlbytes{CR_BYTE, LF_BYTE} var WHITESPACE ctlbytes = ctlbytes{SPACE_BYTE} // ---------------------------------------------------------------------------- // Services // ---------------------------------------------------------------------------- // Creates the byte buffer that corresponds to the specified Command and // provided command arguments. // // TODO: tedious but need to check for errors on all buffer writes .. // func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) { cmd_bytes := []byte(cmd.Code) buffer := bytes.NewBufferString("") buffer.WriteByte (COUNT_BYTE); buffer.Write ([]byte (strconv.Itoa(len(args)+1))) buffer.Write (CRLF); buffer.WriteByte (SIZE_BYTE); buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes)))) buffer.Write (CRLF); buffer.Write (cmd_bytes); buffer.Write (CRLF); for _, s := range args { buffer.WriteByte (SIZE_BYTE); buffer.Write([]byte(strconv.Itoa(len(s)))) buffer.Write(CRLF); buffer.Write(s); buffer.Write(CRLF); } return buffer.Bytes(), nil } // Creates a specific Future type for the given Redis command // and returns it as a generic reference. // func CreateFuture(cmd *Command) (future interface{}) { switch cmd.RespType { case BOOLEAN: future = newFutureBool() case BULK: future = newFutureBytes() case MULTI_BULK: future = newFutureBytesArray() case NUMBER: future = newFutureInt64() case STATUS: // future = newFutureString(); future = newFutureBool() case STRING: future = newFutureString() // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } return } // Sets the type specific result value from the response for the future reference // based on the command type. // func SetFutureResult(future interface{}, cmd *Command, r Response) { if r.IsError() { future.(FutureResult).onError(NewRedisError(r.GetMessage())) } else { switch cmd.RespType { case BOOLEAN: future.(FutureBool).set(r.GetBooleanValue()) case BULK: future.(FutureBytes).set(r.GetBulkData()) case MULTI_BULK: future.(FutureBytesArray).set(r.GetMultiBulkData()) case NUMBER: future.(FutureInt64).set(r.GetNumberValue()) case STATUS: // future.(FutureString).set(r.GetMessage()); future.(FutureBool).set(true) case STRING: future.(FutureString).set(r.GetStringValue()) // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } } } // Gets the response to the command. // Any errors (whether runtime or bugs) are returned as os.Error. // The returned response (regardless of flavor) may have (application level) // errors as sent from Redis server. // func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) { switch cmd.RespType { case BOOLEAN: resp, err = getBooleanResponse(reader, cmd) case BULK: resp, err = getBulkResponse(reader, cmd) case MULTI_BULK: resp, err = getMultiBulkResponse(reader, cmd) case NUMBER: resp, err = getNumberResponse(reader, cmd) case STATUS: resp, err = getStatusResponse(reader, cmd) case STRING: resp, err = getStringResponse(reader, cmd) // case VIRTUAL: // resp, err = getVirtualResponse (); } return } // ---------------------------------------------------------------------------- // internal ops // ---------------------------------------------------------------------------- func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { // fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code); buff, error, fault := readLine(conn) if fault == nil { line := bytes.NewBuffer(buff).String() // fmt.Printf("getStatusResponse: %s\n", line); resp = newStatusResponse(line, error) } return resp, fault } func getBooleanResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { b := buff[1] == TRUE_BYTE resp = newBooleanResponse(b, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] str := bytes.NewBuffer(buff).String() resp = newStringResponse(str, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] numrep := bytes.NewBuffer(buff).String() num, err := strconv.Atoi64(numrep) if err == nil { resp = newNumberResponse(num, error) } else { e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String()) } } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func btoi64(buff []byte) (num int64, e os.Error) { numrep := bytes.NewBuffer(buff).String() num, e = strconv.Atoi64(numrep) if e != nil { e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String()) } return } func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } // log.Println("bulk data size: ", num); if num < 0 { return newBulkResponse(nil, false), nil } bulkdata, e3 := readBulkData(conn, num) if e3 != nil { return nil, e3 } return newBulkResponse(bulkdata, false), nil } func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != COUNT_BYTE { return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } log.Println("multibulk data count: ", num) if num < 0 { return newMultiBulkResponse(nil, false), nil } multibulkdata := make([][]byte, num) for i := int64(0); i < num; i++
return newMultiBulkResponse(multibulkdata, false), nil } // ---------------------------------------------------------------------------- // Response // ---------------------------------------------------------------------------- type Response interface { IsError() bool GetMessage() string GetBooleanValue() bool GetNumberValue() int64 GetStringValue() string GetBulkData() []byte GetMultiBulkData() [][]byte } type _response struct { isError bool msg string boolval bool numval int64 stringval string bulkdata []byte multibulkdata [][]byte } func (r *_response) IsError() bool { return r.isError } func (r *_response) GetMessage() string { return r.msg } func (r *_response) GetBooleanValue() bool { return r.boolval } func (r *_response) GetNumberValue() int64 { return r.numval } func (r *_response) GetStringValue() string { return r.stringval } func (r *_response) GetBulkData() []byte { return r.bulkdata } func (r *_response) GetMultiBulkData() [][]byte { return r.multibulkdata } func newAndInitResponse(isError bool) (r *_response) { r = new(_response) r.isError = isError r.bulkdata = nil r.multibulkdata = nil return } func newStatusResponse(msg string, isError bool) Response { r := newAndInitResponse(isError) r.msg = msg return r } func newBooleanResponse(val bool, isError bool) Response { r := newAndInitResponse(isError) r.boolval = val return r } func newNumberResponse(val int64, isError bool) Response { r := newAndInitResponse(isError) r.numval = val return r } func newStringResponse(val string, isError bool) Response { r := newAndInitResponse(isError) r.stringval = val return r } func newBulkResponse(val []byte, isError bool) Response { r := newAndInitResponse(isError) r.bulkdata = val return r } func newMultiBulkResponse(val [][]byte, isError bool) Response { r := newAndInitResponse(isError) r.multibulkdata = val return r } // ---------------------------------------------------------------------------- // Protocol i/o // ---------------------------------------------------------------------------- // reads all bytes upto CR-LF. (Will eat those last two bytes) // return the line []byte up to CR-LF // error returned is NOT ("-ERR ..."). If there is a Redis error // that is in the line buffer returned func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) { // reader := bufio.NewReader(conn); var buf []byte buf, err = reader.ReadBytes(CR_BYTE) if err == nil { var b byte b, err = reader.ReadByte() if err != nil { return } if b != LF_BYTE { err = os.NewError("<BUG> Expecting a Linefeed byte here!") } // log.Println("readToCRLF: ", buf); buffer = buf[0 : len(buf)-1] } return } func readLine(conn *bufio.Reader) (buf []byte, error bool, fault os.Error) { buf, fault = readToCRLF(conn) if fault == nil { error = buf[0] == ERR_BYTE } return } func readBulkData(conn *bufio.Reader, len int64) ([]byte, os.Error) { buff := make([]byte, len) _, e := io.ReadFull(conn, buff) if e != nil { return nil, NewErrorWithCause(SYSTEM_ERR, "Error while attempting read of bulkdata", e) } // fmt.Println ("Read ", n, " bytes. data: ", buff); crb, e1 := conn.ReadByte() if e1 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal CR:" + e1.String()) } if crb != CR_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not CR as expected") } lfb, e2 := conn.ReadByte() if e2 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal LF:" + e2.String()) } if lfb != LF_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not LF as expected.") } return buff, nil } // convenience func for now // but slated to optimize converting ints to their []byte literal representation func writeNum(b *bytes.Buffer, n int) (*bytes.Buffer, os.Error) { nb := ([]byte (strconv.Itoa(n))) b.Write(nb) return b, nil }
{ sbuf, e := readToCRLF(conn) if e != nil { return nil, e } if sbuf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE for data item in getMultiBulkResponse") } size, e2 := btoi64(sbuf[1:len(sbuf)]) if e2 != nil { return nil, e2 } // log.Println("item: bulk data size: ", size); if size < 0 { multibulkdata[i] = nil } else { bulkdata, e3 := readBulkData(conn, size) if e3 != nil { return nil, e3 } multibulkdata[i] = bulkdata } }
conditional_block
protocol.go
// Copyright 2009 Joubin Houshyar // // 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. // /* */ package redis import ( "os" "io" "bufio" "strconv" "bytes" "log" // "fmt" ) // ---------------------------------------------------------------------------- // Wire // ---------------------------------------------------------------------------- // protocol's special bytes const ( CR_BYTE byte = byte('\r') LF_BYTE = byte('\n') SPACE_BYTE = byte(' ') ERR_BYTE = byte(45) OK_BYTE = byte(43) COUNT_BYTE = byte(42) SIZE_BYTE = byte(36) NUM_BYTE = byte(58) FALSE_BYTE = byte(48) TRUE_BYTE = byte(49) ) type ctlbytes []byte var CRLF ctlbytes = ctlbytes{CR_BYTE, LF_BYTE} var WHITESPACE ctlbytes = ctlbytes{SPACE_BYTE} // ---------------------------------------------------------------------------- // Services // ---------------------------------------------------------------------------- // Creates the byte buffer that corresponds to the specified Command and // provided command arguments. // // TODO: tedious but need to check for errors on all buffer writes .. // func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) { cmd_bytes := []byte(cmd.Code) buffer := bytes.NewBufferString("") buffer.WriteByte (COUNT_BYTE); buffer.Write ([]byte (strconv.Itoa(len(args)+1))) buffer.Write (CRLF); buffer.WriteByte (SIZE_BYTE); buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes)))) buffer.Write (CRLF); buffer.Write (cmd_bytes); buffer.Write (CRLF); for _, s := range args { buffer.WriteByte (SIZE_BYTE); buffer.Write([]byte(strconv.Itoa(len(s)))) buffer.Write(CRLF); buffer.Write(s); buffer.Write(CRLF); } return buffer.Bytes(), nil } // Creates a specific Future type for the given Redis command // and returns it as a generic reference. // func CreateFuture(cmd *Command) (future interface{}) { switch cmd.RespType { case BOOLEAN: future = newFutureBool() case BULK: future = newFutureBytes() case MULTI_BULK: future = newFutureBytesArray() case NUMBER: future = newFutureInt64() case STATUS: // future = newFutureString(); future = newFutureBool() case STRING: future = newFutureString() // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } return } // Sets the type specific result value from the response for the future reference // based on the command type. // func SetFutureResult(future interface{}, cmd *Command, r Response) { if r.IsError() { future.(FutureResult).onError(NewRedisError(r.GetMessage())) } else { switch cmd.RespType { case BOOLEAN: future.(FutureBool).set(r.GetBooleanValue()) case BULK: future.(FutureBytes).set(r.GetBulkData()) case MULTI_BULK: future.(FutureBytesArray).set(r.GetMultiBulkData()) case NUMBER: future.(FutureInt64).set(r.GetNumberValue()) case STATUS: // future.(FutureString).set(r.GetMessage()); future.(FutureBool).set(true) case STRING: future.(FutureString).set(r.GetStringValue()) // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } } } // Gets the response to the command. // Any errors (whether runtime or bugs) are returned as os.Error. // The returned response (regardless of flavor) may have (application level) // errors as sent from Redis server. // func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) { switch cmd.RespType { case BOOLEAN: resp, err = getBooleanResponse(reader, cmd) case BULK: resp, err = getBulkResponse(reader, cmd) case MULTI_BULK: resp, err = getMultiBulkResponse(reader, cmd) case NUMBER: resp, err = getNumberResponse(reader, cmd) case STATUS: resp, err = getStatusResponse(reader, cmd) case STRING: resp, err = getStringResponse(reader, cmd) // case VIRTUAL: // resp, err = getVirtualResponse (); } return } // ---------------------------------------------------------------------------- // internal ops // ---------------------------------------------------------------------------- func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { // fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code); buff, error, fault := readLine(conn) if fault == nil { line := bytes.NewBuffer(buff).String() // fmt.Printf("getStatusResponse: %s\n", line); resp = newStatusResponse(line, error) } return resp, fault } func getBooleanResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { b := buff[1] == TRUE_BYTE resp = newBooleanResponse(b, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] str := bytes.NewBuffer(buff).String() resp = newStringResponse(str, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] numrep := bytes.NewBuffer(buff).String() num, err := strconv.Atoi64(numrep) if err == nil { resp = newNumberResponse(num, error) } else { e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String()) } } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func btoi64(buff []byte) (num int64, e os.Error) { numrep := bytes.NewBuffer(buff).String() num, e = strconv.Atoi64(numrep) if e != nil { e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String()) } return } func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } // log.Println("bulk data size: ", num); if num < 0 { return newBulkResponse(nil, false), nil } bulkdata, e3 := readBulkData(conn, num) if e3 != nil { return nil, e3 } return newBulkResponse(bulkdata, false), nil } func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != COUNT_BYTE { return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } log.Println("multibulk data count: ", num) if num < 0 { return newMultiBulkResponse(nil, false), nil } multibulkdata := make([][]byte, num) for i := int64(0); i < num; i++ { sbuf, e := readToCRLF(conn) if e != nil { return nil, e } if sbuf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE for data item in getMultiBulkResponse") } size, e2 := btoi64(sbuf[1:len(sbuf)]) if e2 != nil { return nil, e2 } // log.Println("item: bulk data size: ", size); if size < 0 { multibulkdata[i] = nil } else { bulkdata, e3 := readBulkData(conn, size) if e3 != nil { return nil, e3 } multibulkdata[i] = bulkdata } } return newMultiBulkResponse(multibulkdata, false), nil } // ---------------------------------------------------------------------------- // Response // ---------------------------------------------------------------------------- type Response interface { IsError() bool GetMessage() string GetBooleanValue() bool GetNumberValue() int64 GetStringValue() string GetBulkData() []byte GetMultiBulkData() [][]byte } type _response struct { isError bool msg string boolval bool numval int64 stringval string bulkdata []byte multibulkdata [][]byte } func (r *_response) IsError() bool { return r.isError } func (r *_response) GetMessage() string { return r.msg } func (r *_response) GetBooleanValue() bool { return r.boolval } func (r *_response) GetNumberValue() int64 { return r.numval } func (r *_response) GetStringValue() string { return r.stringval } func (r *_response) GetBulkData() []byte { return r.bulkdata } func (r *_response) GetMultiBulkData() [][]byte { return r.multibulkdata } func newAndInitResponse(isError bool) (r *_response) { r = new(_response) r.isError = isError r.bulkdata = nil r.multibulkdata = nil return } func newStatusResponse(msg string, isError bool) Response { r := newAndInitResponse(isError) r.msg = msg return r } func newBooleanResponse(val bool, isError bool) Response { r := newAndInitResponse(isError) r.boolval = val return r } func newNumberResponse(val int64, isError bool) Response { r := newAndInitResponse(isError) r.numval = val return r } func newStringResponse(val string, isError bool) Response { r := newAndInitResponse(isError) r.stringval = val return r } func newBulkResponse(val []byte, isError bool) Response { r := newAndInitResponse(isError) r.bulkdata = val return r } func newMultiBulkResponse(val [][]byte, isError bool) Response { r := newAndInitResponse(isError) r.multibulkdata = val return r } // ---------------------------------------------------------------------------- // Protocol i/o // ---------------------------------------------------------------------------- // reads all bytes upto CR-LF. (Will eat those last two bytes) // return the line []byte up to CR-LF // error returned is NOT ("-ERR ..."). If there is a Redis error // that is in the line buffer returned func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) { // reader := bufio.NewReader(conn); var buf []byte buf, err = reader.ReadBytes(CR_BYTE) if err == nil { var b byte b, err = reader.ReadByte() if err != nil { return } if b != LF_BYTE { err = os.NewError("<BUG> Expecting a Linefeed byte here!") } // log.Println("readToCRLF: ", buf); buffer = buf[0 : len(buf)-1] } return } func readLine(conn *bufio.Reader) (buf []byte, error bool, fault os.Error) { buf, fault = readToCRLF(conn) if fault == nil { error = buf[0] == ERR_BYTE } return } func readBulkData(conn *bufio.Reader, len int64) ([]byte, os.Error) { buff := make([]byte, len) _, e := io.ReadFull(conn, buff) if e != nil { return nil, NewErrorWithCause(SYSTEM_ERR, "Error while attempting read of bulkdata", e) } // fmt.Println ("Read ", n, " bytes. data: ", buff); crb, e1 := conn.ReadByte() if e1 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal CR:" + e1.String()) } if crb != CR_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not CR as expected") } lfb, e2 := conn.ReadByte() if e2 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal LF:" + e2.String()) } if lfb != LF_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not LF as expected.") } return buff, nil } // convenience func for now // but slated to optimize converting ints to their []byte literal representation func
(b *bytes.Buffer, n int) (*bytes.Buffer, os.Error) { nb := ([]byte (strconv.Itoa(n))) b.Write(nb) return b, nil }
writeNum
identifier_name
protocol.go
// Copyright 2009 Joubin Houshyar // // 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. // /* */ package redis import ( "os" "io" "bufio" "strconv" "bytes" "log" // "fmt" ) // ---------------------------------------------------------------------------- // Wire // ---------------------------------------------------------------------------- // protocol's special bytes const ( CR_BYTE byte = byte('\r') LF_BYTE = byte('\n') SPACE_BYTE = byte(' ') ERR_BYTE = byte(45) OK_BYTE = byte(43) COUNT_BYTE = byte(42) SIZE_BYTE = byte(36) NUM_BYTE = byte(58) FALSE_BYTE = byte(48) TRUE_BYTE = byte(49) ) type ctlbytes []byte var CRLF ctlbytes = ctlbytes{CR_BYTE, LF_BYTE} var WHITESPACE ctlbytes = ctlbytes{SPACE_BYTE} // ---------------------------------------------------------------------------- // Services // ---------------------------------------------------------------------------- // Creates the byte buffer that corresponds to the specified Command and // provided command arguments. // // TODO: tedious but need to check for errors on all buffer writes .. // func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) { cmd_bytes := []byte(cmd.Code) buffer := bytes.NewBufferString("") buffer.WriteByte (COUNT_BYTE); buffer.Write ([]byte (strconv.Itoa(len(args)+1))) buffer.Write (CRLF); buffer.WriteByte (SIZE_BYTE); buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes)))) buffer.Write (CRLF); buffer.Write (cmd_bytes); buffer.Write (CRLF); for _, s := range args { buffer.WriteByte (SIZE_BYTE); buffer.Write([]byte(strconv.Itoa(len(s)))) buffer.Write(CRLF); buffer.Write(s); buffer.Write(CRLF); } return buffer.Bytes(), nil } // Creates a specific Future type for the given Redis command // and returns it as a generic reference. // func CreateFuture(cmd *Command) (future interface{}) { switch cmd.RespType { case BOOLEAN: future = newFutureBool() case BULK: future = newFutureBytes() case MULTI_BULK: future = newFutureBytesArray() case NUMBER: future = newFutureInt64() case STATUS: // future = newFutureString(); future = newFutureBool() case STRING: future = newFutureString() // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } return } // Sets the type specific result value from the response for the future reference // based on the command type. // func SetFutureResult(future interface{}, cmd *Command, r Response) { if r.IsError() { future.(FutureResult).onError(NewRedisError(r.GetMessage())) } else { switch cmd.RespType { case BOOLEAN: future.(FutureBool).set(r.GetBooleanValue()) case BULK: future.(FutureBytes).set(r.GetBulkData()) case MULTI_BULK: future.(FutureBytesArray).set(r.GetMultiBulkData()) case NUMBER: future.(FutureInt64).set(r.GetNumberValue()) case STATUS: // future.(FutureString).set(r.GetMessage()); future.(FutureBool).set(true) case STRING: future.(FutureString).set(r.GetStringValue()) // case VIRTUAL: // TODO // resp, err = getVirtualResponse (); } } } // Gets the response to the command. // Any errors (whether runtime or bugs) are returned as os.Error. // The returned response (regardless of flavor) may have (application level) // errors as sent from Redis server. // func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) { switch cmd.RespType { case BOOLEAN: resp, err = getBooleanResponse(reader, cmd) case BULK: resp, err = getBulkResponse(reader, cmd) case MULTI_BULK: resp, err = getMultiBulkResponse(reader, cmd) case NUMBER: resp, err = getNumberResponse(reader, cmd) case STATUS: resp, err = getStatusResponse(reader, cmd) case STRING: resp, err = getStringResponse(reader, cmd) // case VIRTUAL: // resp, err = getVirtualResponse (); } return } // ---------------------------------------------------------------------------- // internal ops // ---------------------------------------------------------------------------- func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { // fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code); buff, error, fault := readLine(conn) if fault == nil { line := bytes.NewBuffer(buff).String() // fmt.Printf("getStatusResponse: %s\n", line); resp = newStatusResponse(line, error) } return resp, fault } func getBooleanResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { b := buff[1] == TRUE_BYTE resp = newBooleanResponse(b, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] str := bytes.NewBuffer(buff).String() resp = newStringResponse(str, error) } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) { buff, error, fault := readLine(conn) if fault == nil { if !error { buff = buff[1:len(buff)] numrep := bytes.NewBuffer(buff).String() num, err := strconv.Atoi64(numrep) if err == nil { resp = newNumberResponse(num, error) } else { e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String()) } } else { resp = newStatusResponse(bytes.NewBuffer(buff).String(), error) } } return resp, fault } func btoi64(buff []byte) (num int64, e os.Error) { numrep := bytes.NewBuffer(buff).String() num, e = strconv.Atoi64(numrep) if e != nil { e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String()) } return } func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } // log.Println("bulk data size: ", num); if num < 0 { return newBulkResponse(nil, false), nil } bulkdata, e3 := readBulkData(conn, num) if e3 != nil { return nil, e3 } return newBulkResponse(bulkdata, false), nil } func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) { buf, e1 := readToCRLF(conn) if e1 != nil { return nil, e1 } if buf[0] == ERR_BYTE { return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil } if buf[0] != COUNT_BYTE { return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse") } num, e2 := btoi64(buf[1:len(buf)]) if e2 != nil { return nil, e2 } log.Println("multibulk data count: ", num) if num < 0 { return newMultiBulkResponse(nil, false), nil } multibulkdata := make([][]byte, num) for i := int64(0); i < num; i++ { sbuf, e := readToCRLF(conn) if e != nil { return nil, e } if sbuf[0] != SIZE_BYTE { return nil, os.NewError("<BUG> Expecting a SIZE_BYTE for data item in getMultiBulkResponse") } size, e2 := btoi64(sbuf[1:len(sbuf)]) if e2 != nil { return nil, e2 } // log.Println("item: bulk data size: ", size); if size < 0 { multibulkdata[i] = nil } else { bulkdata, e3 := readBulkData(conn, size) if e3 != nil { return nil, e3 } multibulkdata[i] = bulkdata
} } return newMultiBulkResponse(multibulkdata, false), nil } // ---------------------------------------------------------------------------- // Response // ---------------------------------------------------------------------------- type Response interface { IsError() bool GetMessage() string GetBooleanValue() bool GetNumberValue() int64 GetStringValue() string GetBulkData() []byte GetMultiBulkData() [][]byte } type _response struct { isError bool msg string boolval bool numval int64 stringval string bulkdata []byte multibulkdata [][]byte } func (r *_response) IsError() bool { return r.isError } func (r *_response) GetMessage() string { return r.msg } func (r *_response) GetBooleanValue() bool { return r.boolval } func (r *_response) GetNumberValue() int64 { return r.numval } func (r *_response) GetStringValue() string { return r.stringval } func (r *_response) GetBulkData() []byte { return r.bulkdata } func (r *_response) GetMultiBulkData() [][]byte { return r.multibulkdata } func newAndInitResponse(isError bool) (r *_response) { r = new(_response) r.isError = isError r.bulkdata = nil r.multibulkdata = nil return } func newStatusResponse(msg string, isError bool) Response { r := newAndInitResponse(isError) r.msg = msg return r } func newBooleanResponse(val bool, isError bool) Response { r := newAndInitResponse(isError) r.boolval = val return r } func newNumberResponse(val int64, isError bool) Response { r := newAndInitResponse(isError) r.numval = val return r } func newStringResponse(val string, isError bool) Response { r := newAndInitResponse(isError) r.stringval = val return r } func newBulkResponse(val []byte, isError bool) Response { r := newAndInitResponse(isError) r.bulkdata = val return r } func newMultiBulkResponse(val [][]byte, isError bool) Response { r := newAndInitResponse(isError) r.multibulkdata = val return r } // ---------------------------------------------------------------------------- // Protocol i/o // ---------------------------------------------------------------------------- // reads all bytes upto CR-LF. (Will eat those last two bytes) // return the line []byte up to CR-LF // error returned is NOT ("-ERR ..."). If there is a Redis error // that is in the line buffer returned func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) { // reader := bufio.NewReader(conn); var buf []byte buf, err = reader.ReadBytes(CR_BYTE) if err == nil { var b byte b, err = reader.ReadByte() if err != nil { return } if b != LF_BYTE { err = os.NewError("<BUG> Expecting a Linefeed byte here!") } // log.Println("readToCRLF: ", buf); buffer = buf[0 : len(buf)-1] } return } func readLine(conn *bufio.Reader) (buf []byte, error bool, fault os.Error) { buf, fault = readToCRLF(conn) if fault == nil { error = buf[0] == ERR_BYTE } return } func readBulkData(conn *bufio.Reader, len int64) ([]byte, os.Error) { buff := make([]byte, len) _, e := io.ReadFull(conn, buff) if e != nil { return nil, NewErrorWithCause(SYSTEM_ERR, "Error while attempting read of bulkdata", e) } // fmt.Println ("Read ", n, " bytes. data: ", buff); crb, e1 := conn.ReadByte() if e1 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal CR:" + e1.String()) } if crb != CR_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not CR as expected") } lfb, e2 := conn.ReadByte() if e2 != nil { return nil, os.NewError("Error while attempting read of bulkdata terminal LF:" + e2.String()) } if lfb != LF_BYTE { return nil, os.NewError("<BUG> bulkdata terminal was not LF as expected.") } return buff, nil } // convenience func for now // but slated to optimize converting ints to their []byte literal representation func writeNum(b *bytes.Buffer, n int) (*bytes.Buffer, os.Error) { nb := ([]byte (strconv.Itoa(n))) b.Write(nb) return b, nil }
random_line_split
teste.py
import numpy as np import cv2 from scipy import ndimage import math import csv BRANCO = 255 vizinhos = [[0,0],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1]] #verifica se o ponto pertence a uma fronteira def bool_nas_Fronteiras(ponto, listaDeFronteiras):
#retorna a posição de um pixel branco def encontrar_prox_branco(ponto, img): i, j = ponto row, col = img.shape while(i<row): while (j<col): if img[i,j] >= BRANCO: return(i,j) j+=1 j=0 i+=1 return (i-1,j) #retorna o proximo ponto diferente de branco e que não esta na lista de fronteiras def find_next_point(img, last_pixel, listaDeFronteiras): i, j = last_pixel row, col = img.shape i+=1 while(i<row): while (j<col): if img[i,j] < BRANCO and img[i, j-1] >= BRANCO: if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto return (i,j) else:#percorre a imagem ate achar um branco ponto_branco = encontrar_prox_branco((i,j), img) i=ponto_branco[0] j=ponto_branco[1] continue j+=1 j=0 i+=1 return 0 def boolPontoNaBorda(ponto, fronteira): return ponto in fronteira #encontrou o primeiro pronto da lista de fronteira #encontra o primeiro pixel diferente de branco def find_no_white(img): row, col = img.shape for i in range(row): for j in range(col): if img[i,j] < BRANCO: return (i,j)#retorna a posição do pixel #retorna a posição do array vizinhos def obterVizinhoID(x, y): for i in range(9): if(x == vizinhos[i][0] and y == vizinhos[i][1]): return i #a partir de um pixel inicial percorre a borda da folha def seguidorDeFronteira(img, first_pixel, i): row, col = img.shape fronteira=[] fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira x = 0 y = 1 #intuito de deixar o código mais legível b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y c_0 = [0, -1] anterior_b0 = [0, 0] cont = 1 contador_de_vizinhos = 0 find_init_border = True contador=0 while(find_init_border): indexVizinho=obterVizinhoID(c_0[x], c_0[y]) while(True): if(indexVizinho == 8):#zerar o clock indexVizinho = 0 proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO b_0 = [proxB_0[x], proxB_0[y]] check = (b_0[x],b_0[y]) if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira find_init_border = False break else: fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]] contador_de_vizinhos = 0 contador+=1 if proxB_0[x] > row: #para quando sair da imagem return False, (0,0) break contador_de_vizinhos +=1 if contador_de_vizinhos == 9: #para quando estiver um loop infinito return False, (0,0) cont = 0 anterior_b0 = [proxB_0[x], proxB_0[y]] indexVizinho += 1 #incrementa o vizinho tamanho = len(fronteira) if tamanho>50 and tamanho<25000: #tratamento da imagem 13 return True, fronteira return False, (0,0) def grayscale(img): row, col, bpp = np.shape(img) img_gray = [] for i in range(0,row): for j in range(0,col): b = int(img[i][j][0]) g = int(img[i][j][1]) r = int(img[i][j][2]) pixel = int((b+g+r) / 3) img_gray.append(pixel) return img_gray def remove_ruidos(imagem): img = imagem.astype('float') img = img[:,:,0] # convert to 2D array gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza _,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario img = cv2.medianBlur(img, 5) # remove o ruido return img #inicio do algoritmo seguidor de fronteiras def init(img): listaDeFronteiras=[] first_no_white_pixel = find_no_white(img) next_pixel = first_no_white_pixel i=0 while(next_pixel!=0): try: is_fronteira, fronteira = seguidorDeFronteira(img, next_pixel, i) if is_fronteira: #caso seja uma fronteira valida listaDeFronteiras.append(fronteira) last_pixel = next_pixel next_pixel = find_next_point(img, last_pixel, listaDeFronteiras) except Exception as e: print(e) i+=1 #este tratamento funciona devido a imagem 13 for front in listaDeFronteiras: if len(front) > 19000: listaDeFronteiras.remove(front) print("NUMERO DE FOLHAS ENCONTRADAS:") print(len(listaDeFronteiras)) return listaDeFronteiras #retorna a altura, largura, menor linha e menor coluna def encontra_dimensoes(fronteira): x = 0 y = 1 list_y = [cord_y[y] for cord_y in fronteira] list_x = [cord_x[x] for cord_x in fronteira] x_menor = list_x[0] #pega a primeira posicao x_maior = max(list_x) y_menor = min(list_y) y_maior = max(list_y) #+3 serve para adicionar uma borda branca return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor #cria a imagem da fronteira e retorna uma imagem com a mascara def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img): row, col, bpp = img_borda.shape img_borda_binaria = np.zeros((row, col)) for pixel in fronteira: #transalada os pixeis nova_coordenada_x = (int(pixel[0])-menor_x)+1 nova_coordenada_y = (int(pixel[1])-menor_y)+1 img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0 #criando imagem binaria img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1 nome_imagem = name_img + '-' + str(index) +"-P"+ ".png" cv2.imwrite(nome_imagem, img_borda) img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int) return img_borda_binaria def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img): row, col, bpp = np.shape(imagem_branca) for i in range(row): for j in range(col): if img_borda_binaria[i][j] == 1: nova_coordenada_x = i+menor_x+1 nova_coordenada_y = j+menor_y+1 imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0] imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1] imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2] nome_imagem = name_img + '-' + str(index) + ".png" cv2.imwrite(nome_imagem, imagem_branca) return imagem_branca def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img): index = 1 for fronteira in lista_fronteiras: row, col, menor_x, menor_y = encontra_dimensoes(fronteira) #salavando a borda imagem_branca = np.ones((row, col, 3)) * 255 img_borda_binaria = criar_imagem_borda(imagem_branca, fronteira, menor_x, menor_y, index, name_img) #salvando a folha criar_imagem_unica_folha_colorida(imagem_sem_ruido, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img) index += 1 def valor_medio(histograma, lista_probabilidade): media = 0 j = 0 for i in histograma: media += i * lista_probabilidade[j] j += 1 return media def pixeis_coloridos(histograma): total = 0 for i in histograma: total += histograma[i] return total def probabilidade_de_cada_cor(histograma): lista_probabilidade = [] total_pixeis_coloridos = pixeis_coloridos(histograma) for i in histograma: probabilidade = histograma[i] / total_pixeis_coloridos lista_probabilidade.append(probabilidade) return lista_probabilidade def obter_histograma(imagem): histograma = {} img_gray = grayscale(imagem) #converte para tons de cinza arrendondando o valor for cor in img_gray: if cor != BRANCO: if cor in histograma.keys(): histograma[cor] += 1 else: histograma[cor] = 1 return histograma #função que retorna a media, variancia, uniformidade, entropia de cada folha def analise_textura(name_img, img_number): name_img = name_img + '-' + str(img_number) + ".png" imagem = cv2.imread(name_img) histograma = obter_histograma(imagem) probabilidade = probabilidade_de_cada_cor(histograma) media = valor_medio(histograma, probabilidade) j = 0 variancia = uniformidade = entropia = 0 for i in histograma: variancia += (((i-media)**2) * probabilidade[j]) uniformidade += (probabilidade[j] ** 2) entropia += (probabilidade[j] * np.log2(probabilidade[j])) * -1 j += 1 return media, variancia, uniformidade, entropia #realiza o tratamento do nome da imagem 1 -> Teste01 retorna o nome e a imagem do disco def pegar_nome(img_number): name_img = 'Folhas/Teste' if(img_number < 10): name_img = name_img + '0' name_img = name_img + str(img_number) + '.png' imagem = cv2.imread(name_img) name_img = name_img.split(".")[0] return imagem, name_img #cria a planilha .csv e adiciona os cabeçalhos def criar_planilha(): planilha = csv.writer(open("SAIDAS.csv", "w")) planilha.writerow(["ID imagem", "ID folha", "Media", "Variancia", "Uniformidade", "Entropia", "Perimetro"]) return planilha #escreve na planilha os dados obtidos de cada folha def incrementar_planilha(planilha, id_img, id_folha, media, variancia, uniformidade, entropia, perimetro): id_img = id_img.removeprefix('Folhas/') planilha.writerow([id_img, id_folha, media, variancia, uniformidade, entropia, perimetro]) #função principal do código qual chama as funções de execução def main(): print("Bem Vindo ao Trabalho de PID") img_number = 1 planilha = criar_planilha() while(True): try: imagem, name_img = pegar_nome(img_number) img_sem_ruido = remove_ruidos(imagem) lista_fronteiras = [] print("Encontrando todas as bordas de: ", name_img) print(" Este processo pode demorar um pouco") lista_fronteiras = init(img_sem_ruido) #encontrar as bordas recorta_imagem(lista_fronteiras, img_sem_ruido, imagem, name_img) # recortar as folhas e salvar em disco (salvar a borda e a folha colorida) print("Analisando a textura das folhas encontradas") index_sub_folha = 1 while True: try: media, variancia, uniformidade, entropia = analise_textura(name_img, index_sub_folha) perimetro = len(lista_fronteiras[index_sub_folha-1]) incrementar_planilha(planilha, name_img, index_sub_folha, media, variancia, uniformidade, entropia, perimetro) index_sub_folha += 1 except: print("Fim da análise de textura para todas as folhas encontradas no arquivo: ", name_img) break img_number += 1 except: print("Acabou :) EBAA!") break if __name__ == "__main__": main()
for f in listaDeFronteiras: if boolPontoNaBorda(ponto, f): return True return False
identifier_body
teste.py
import numpy as np import cv2 from scipy import ndimage import math import csv BRANCO = 255 vizinhos = [[0,0],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1]] #verifica se o ponto pertence a uma fronteira def bool_nas_Fronteiras(ponto, listaDeFronteiras): for f in listaDeFronteiras: if boolPontoNaBorda(ponto, f): return True return False #retorna a posição de um pixel branco def encontrar_prox_branco(ponto, img): i, j = ponto row, col = img.shape while(i<row): while (j<col): if img[i,j] >= BRANCO: return(i,j) j+=1 j=0 i+=1 return (i-1,j) #retorna o proximo ponto diferente de branco e que não esta na lista de fronteiras def find_next_point(img, last_pixel, listaDeFronteiras): i, j = last_pixel row, col = img.shape i+=1 while(i<row): while (j<col): if img[i,j] < BRANCO and img[i, j-1] >= BRANCO: if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto return (i,j) else:#percorre a imagem ate achar um branco ponto_branco = encontrar_prox_branco((i,j), img) i=ponto_branco[0]
i+=1 return 0 def boolPontoNaBorda(ponto, fronteira): return ponto in fronteira #encontrou o primeiro pronto da lista de fronteira #encontra o primeiro pixel diferente de branco def find_no_white(img): row, col = img.shape for i in range(row): for j in range(col): if img[i,j] < BRANCO: return (i,j)#retorna a posição do pixel #retorna a posição do array vizinhos def obterVizinhoID(x, y): for i in range(9): if(x == vizinhos[i][0] and y == vizinhos[i][1]): return i #a partir de um pixel inicial percorre a borda da folha def seguidorDeFronteira(img, first_pixel, i): row, col = img.shape fronteira=[] fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira x = 0 y = 1 #intuito de deixar o código mais legível b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y c_0 = [0, -1] anterior_b0 = [0, 0] cont = 1 contador_de_vizinhos = 0 find_init_border = True contador=0 while(find_init_border): indexVizinho=obterVizinhoID(c_0[x], c_0[y]) while(True): if(indexVizinho == 8):#zerar o clock indexVizinho = 0 proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO b_0 = [proxB_0[x], proxB_0[y]] check = (b_0[x],b_0[y]) if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira find_init_border = False break else: fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]] contador_de_vizinhos = 0 contador+=1 if proxB_0[x] > row: #para quando sair da imagem return False, (0,0) break contador_de_vizinhos +=1 if contador_de_vizinhos == 9: #para quando estiver um loop infinito return False, (0,0) cont = 0 anterior_b0 = [proxB_0[x], proxB_0[y]] indexVizinho += 1 #incrementa o vizinho tamanho = len(fronteira) if tamanho>50 and tamanho<25000: #tratamento da imagem 13 return True, fronteira return False, (0,0) def grayscale(img): row, col, bpp = np.shape(img) img_gray = [] for i in range(0,row): for j in range(0,col): b = int(img[i][j][0]) g = int(img[i][j][1]) r = int(img[i][j][2]) pixel = int((b+g+r) / 3) img_gray.append(pixel) return img_gray def remove_ruidos(imagem): img = imagem.astype('float') img = img[:,:,0] # convert to 2D array gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza _,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario img = cv2.medianBlur(img, 5) # remove o ruido return img #inicio do algoritmo seguidor de fronteiras def init(img): listaDeFronteiras=[] first_no_white_pixel = find_no_white(img) next_pixel = first_no_white_pixel i=0 while(next_pixel!=0): try: is_fronteira, fronteira = seguidorDeFronteira(img, next_pixel, i) if is_fronteira: #caso seja uma fronteira valida listaDeFronteiras.append(fronteira) last_pixel = next_pixel next_pixel = find_next_point(img, last_pixel, listaDeFronteiras) except Exception as e: print(e) i+=1 #este tratamento funciona devido a imagem 13 for front in listaDeFronteiras: if len(front) > 19000: listaDeFronteiras.remove(front) print("NUMERO DE FOLHAS ENCONTRADAS:") print(len(listaDeFronteiras)) return listaDeFronteiras #retorna a altura, largura, menor linha e menor coluna def encontra_dimensoes(fronteira): x = 0 y = 1 list_y = [cord_y[y] for cord_y in fronteira] list_x = [cord_x[x] for cord_x in fronteira] x_menor = list_x[0] #pega a primeira posicao x_maior = max(list_x) y_menor = min(list_y) y_maior = max(list_y) #+3 serve para adicionar uma borda branca return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor #cria a imagem da fronteira e retorna uma imagem com a mascara def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img): row, col, bpp = img_borda.shape img_borda_binaria = np.zeros((row, col)) for pixel in fronteira: #transalada os pixeis nova_coordenada_x = (int(pixel[0])-menor_x)+1 nova_coordenada_y = (int(pixel[1])-menor_y)+1 img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0 #criando imagem binaria img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1 nome_imagem = name_img + '-' + str(index) +"-P"+ ".png" cv2.imwrite(nome_imagem, img_borda) img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int) return img_borda_binaria def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img): row, col, bpp = np.shape(imagem_branca) for i in range(row): for j in range(col): if img_borda_binaria[i][j] == 1: nova_coordenada_x = i+menor_x+1 nova_coordenada_y = j+menor_y+1 imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0] imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1] imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2] nome_imagem = name_img + '-' + str(index) + ".png" cv2.imwrite(nome_imagem, imagem_branca) return imagem_branca def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img): index = 1 for fronteira in lista_fronteiras: row, col, menor_x, menor_y = encontra_dimensoes(fronteira) #salavando a borda imagem_branca = np.ones((row, col, 3)) * 255 img_borda_binaria = criar_imagem_borda(imagem_branca, fronteira, menor_x, menor_y, index, name_img) #salvando a folha criar_imagem_unica_folha_colorida(imagem_sem_ruido, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img) index += 1 def valor_medio(histograma, lista_probabilidade): media = 0 j = 0 for i in histograma: media += i * lista_probabilidade[j] j += 1 return media def pixeis_coloridos(histograma): total = 0 for i in histograma: total += histograma[i] return total def probabilidade_de_cada_cor(histograma): lista_probabilidade = [] total_pixeis_coloridos = pixeis_coloridos(histograma) for i in histograma: probabilidade = histograma[i] / total_pixeis_coloridos lista_probabilidade.append(probabilidade) return lista_probabilidade def obter_histograma(imagem): histograma = {} img_gray = grayscale(imagem) #converte para tons de cinza arrendondando o valor for cor in img_gray: if cor != BRANCO: if cor in histograma.keys(): histograma[cor] += 1 else: histograma[cor] = 1 return histograma #função que retorna a media, variancia, uniformidade, entropia de cada folha def analise_textura(name_img, img_number): name_img = name_img + '-' + str(img_number) + ".png" imagem = cv2.imread(name_img) histograma = obter_histograma(imagem) probabilidade = probabilidade_de_cada_cor(histograma) media = valor_medio(histograma, probabilidade) j = 0 variancia = uniformidade = entropia = 0 for i in histograma: variancia += (((i-media)**2) * probabilidade[j]) uniformidade += (probabilidade[j] ** 2) entropia += (probabilidade[j] * np.log2(probabilidade[j])) * -1 j += 1 return media, variancia, uniformidade, entropia #realiza o tratamento do nome da imagem 1 -> Teste01 retorna o nome e a imagem do disco def pegar_nome(img_number): name_img = 'Folhas/Teste' if(img_number < 10): name_img = name_img + '0' name_img = name_img + str(img_number) + '.png' imagem = cv2.imread(name_img) name_img = name_img.split(".")[0] return imagem, name_img #cria a planilha .csv e adiciona os cabeçalhos def criar_planilha(): planilha = csv.writer(open("SAIDAS.csv", "w")) planilha.writerow(["ID imagem", "ID folha", "Media", "Variancia", "Uniformidade", "Entropia", "Perimetro"]) return planilha #escreve na planilha os dados obtidos de cada folha def incrementar_planilha(planilha, id_img, id_folha, media, variancia, uniformidade, entropia, perimetro): id_img = id_img.removeprefix('Folhas/') planilha.writerow([id_img, id_folha, media, variancia, uniformidade, entropia, perimetro]) #função principal do código qual chama as funções de execução def main(): print("Bem Vindo ao Trabalho de PID") img_number = 1 planilha = criar_planilha() while(True): try: imagem, name_img = pegar_nome(img_number) img_sem_ruido = remove_ruidos(imagem) lista_fronteiras = [] print("Encontrando todas as bordas de: ", name_img) print(" Este processo pode demorar um pouco") lista_fronteiras = init(img_sem_ruido) #encontrar as bordas recorta_imagem(lista_fronteiras, img_sem_ruido, imagem, name_img) # recortar as folhas e salvar em disco (salvar a borda e a folha colorida) print("Analisando a textura das folhas encontradas") index_sub_folha = 1 while True: try: media, variancia, uniformidade, entropia = analise_textura(name_img, index_sub_folha) perimetro = len(lista_fronteiras[index_sub_folha-1]) incrementar_planilha(planilha, name_img, index_sub_folha, media, variancia, uniformidade, entropia, perimetro) index_sub_folha += 1 except: print("Fim da análise de textura para todas as folhas encontradas no arquivo: ", name_img) break img_number += 1 except: print("Acabou :) EBAA!") break if __name__ == "__main__": main()
j=ponto_branco[1] continue j+=1 j=0
random_line_split
teste.py
import numpy as np import cv2 from scipy import ndimage import math import csv BRANCO = 255 vizinhos = [[0,0],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1]] #verifica se o ponto pertence a uma fronteira def bool_nas_Fronteiras(ponto, listaDeFronteiras): for f in listaDeFronteiras: if boolPontoNaBorda(ponto, f): return True return False #retorna a posição de um pixel branco def encontrar_prox_branco(ponto, img): i, j = ponto row, col = img.shape while(i<row): while (j<col): if img[i,j] >= BRANCO: re
j+=1 j=0 i+=1 return (i-1,j) #retorna o proximo ponto diferente de branco e que não esta na lista de fronteiras def find_next_point(img, last_pixel, listaDeFronteiras): i, j = last_pixel row, col = img.shape i+=1 while(i<row): while (j<col): if img[i,j] < BRANCO and img[i, j-1] >= BRANCO: if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto return (i,j) else:#percorre a imagem ate achar um branco ponto_branco = encontrar_prox_branco((i,j), img) i=ponto_branco[0] j=ponto_branco[1] continue j+=1 j=0 i+=1 return 0 def boolPontoNaBorda(ponto, fronteira): return ponto in fronteira #encontrou o primeiro pronto da lista de fronteira #encontra o primeiro pixel diferente de branco def find_no_white(img): row, col = img.shape for i in range(row): for j in range(col): if img[i,j] < BRANCO: return (i,j)#retorna a posição do pixel #retorna a posição do array vizinhos def obterVizinhoID(x, y): for i in range(9): if(x == vizinhos[i][0] and y == vizinhos[i][1]): return i #a partir de um pixel inicial percorre a borda da folha def seguidorDeFronteira(img, first_pixel, i): row, col = img.shape fronteira=[] fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira x = 0 y = 1 #intuito de deixar o código mais legível b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y c_0 = [0, -1] anterior_b0 = [0, 0] cont = 1 contador_de_vizinhos = 0 find_init_border = True contador=0 while(find_init_border): indexVizinho=obterVizinhoID(c_0[x], c_0[y]) while(True): if(indexVizinho == 8):#zerar o clock indexVizinho = 0 proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO b_0 = [proxB_0[x], proxB_0[y]] check = (b_0[x],b_0[y]) if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira find_init_border = False break else: fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]] contador_de_vizinhos = 0 contador+=1 if proxB_0[x] > row: #para quando sair da imagem return False, (0,0) break contador_de_vizinhos +=1 if contador_de_vizinhos == 9: #para quando estiver um loop infinito return False, (0,0) cont = 0 anterior_b0 = [proxB_0[x], proxB_0[y]] indexVizinho += 1 #incrementa o vizinho tamanho = len(fronteira) if tamanho>50 and tamanho<25000: #tratamento da imagem 13 return True, fronteira return False, (0,0) def grayscale(img): row, col, bpp = np.shape(img) img_gray = [] for i in range(0,row): for j in range(0,col): b = int(img[i][j][0]) g = int(img[i][j][1]) r = int(img[i][j][2]) pixel = int((b+g+r) / 3) img_gray.append(pixel) return img_gray def remove_ruidos(imagem): img = imagem.astype('float') img = img[:,:,0] # convert to 2D array gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza _,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario img = cv2.medianBlur(img, 5) # remove o ruido return img #inicio do algoritmo seguidor de fronteiras def init(img): listaDeFronteiras=[] first_no_white_pixel = find_no_white(img) next_pixel = first_no_white_pixel i=0 while(next_pixel!=0): try: is_fronteira, fronteira = seguidorDeFronteira(img, next_pixel, i) if is_fronteira: #caso seja uma fronteira valida listaDeFronteiras.append(fronteira) last_pixel = next_pixel next_pixel = find_next_point(img, last_pixel, listaDeFronteiras) except Exception as e: print(e) i+=1 #este tratamento funciona devido a imagem 13 for front in listaDeFronteiras: if len(front) > 19000: listaDeFronteiras.remove(front) print("NUMERO DE FOLHAS ENCONTRADAS:") print(len(listaDeFronteiras)) return listaDeFronteiras #retorna a altura, largura, menor linha e menor coluna def encontra_dimensoes(fronteira): x = 0 y = 1 list_y = [cord_y[y] for cord_y in fronteira] list_x = [cord_x[x] for cord_x in fronteira] x_menor = list_x[0] #pega a primeira posicao x_maior = max(list_x) y_menor = min(list_y) y_maior = max(list_y) #+3 serve para adicionar uma borda branca return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor #cria a imagem da fronteira e retorna uma imagem com a mascara def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img): row, col, bpp = img_borda.shape img_borda_binaria = np.zeros((row, col)) for pixel in fronteira: #transalada os pixeis nova_coordenada_x = (int(pixel[0])-menor_x)+1 nova_coordenada_y = (int(pixel[1])-menor_y)+1 img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0 #criando imagem binaria img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1 nome_imagem = name_img + '-' + str(index) +"-P"+ ".png" cv2.imwrite(nome_imagem, img_borda) img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int) return img_borda_binaria def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img): row, col, bpp = np.shape(imagem_branca) for i in range(row): for j in range(col): if img_borda_binaria[i][j] == 1: nova_coordenada_x = i+menor_x+1 nova_coordenada_y = j+menor_y+1 imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0] imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1] imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2] nome_imagem = name_img + '-' + str(index) + ".png" cv2.imwrite(nome_imagem, imagem_branca) return imagem_branca def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img): index = 1 for fronteira in lista_fronteiras: row, col, menor_x, menor_y = encontra_dimensoes(fronteira) #salavando a borda imagem_branca = np.ones((row, col, 3)) * 255 img_borda_binaria = criar_imagem_borda(imagem_branca, fronteira, menor_x, menor_y, index, name_img) #salvando a folha criar_imagem_unica_folha_colorida(imagem_sem_ruido, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img) index += 1 def valor_medio(histograma, lista_probabilidade): media = 0 j = 0 for i in histograma: media += i * lista_probabilidade[j] j += 1 return media def pixeis_coloridos(histograma): total = 0 for i in histograma: total += histograma[i] return total def probabilidade_de_cada_cor(histograma): lista_probabilidade = [] total_pixeis_coloridos = pixeis_coloridos(histograma) for i in histograma: probabilidade = histograma[i] / total_pixeis_coloridos lista_probabilidade.append(probabilidade) return lista_probabilidade def obter_histograma(imagem): histograma = {} img_gray = grayscale(imagem) #converte para tons de cinza arrendondando o valor for cor in img_gray: if cor != BRANCO: if cor in histograma.keys(): histograma[cor] += 1 else: histograma[cor] = 1 return histograma #função que retorna a media, variancia, uniformidade, entropia de cada folha def analise_textura(name_img, img_number): name_img = name_img + '-' + str(img_number) + ".png" imagem = cv2.imread(name_img) histograma = obter_histograma(imagem) probabilidade = probabilidade_de_cada_cor(histograma) media = valor_medio(histograma, probabilidade) j = 0 variancia = uniformidade = entropia = 0 for i in histograma: variancia += (((i-media)**2) * probabilidade[j]) uniformidade += (probabilidade[j] ** 2) entropia += (probabilidade[j] * np.log2(probabilidade[j])) * -1 j += 1 return media, variancia, uniformidade, entropia #realiza o tratamento do nome da imagem 1 -> Teste01 retorna o nome e a imagem do disco def pegar_nome(img_number): name_img = 'Folhas/Teste' if(img_number < 10): name_img = name_img + '0' name_img = name_img + str(img_number) + '.png' imagem = cv2.imread(name_img) name_img = name_img.split(".")[0] return imagem, name_img #cria a planilha .csv e adiciona os cabeçalhos def criar_planilha(): planilha = csv.writer(open("SAIDAS.csv", "w")) planilha.writerow(["ID imagem", "ID folha", "Media", "Variancia", "Uniformidade", "Entropia", "Perimetro"]) return planilha #escreve na planilha os dados obtidos de cada folha def incrementar_planilha(planilha, id_img, id_folha, media, variancia, uniformidade, entropia, perimetro): id_img = id_img.removeprefix('Folhas/') planilha.writerow([id_img, id_folha, media, variancia, uniformidade, entropia, perimetro]) #função principal do código qual chama as funções de execução def main(): print("Bem Vindo ao Trabalho de PID") img_number = 1 planilha = criar_planilha() while(True): try: imagem, name_img = pegar_nome(img_number) img_sem_ruido = remove_ruidos(imagem) lista_fronteiras = [] print("Encontrando todas as bordas de: ", name_img) print(" Este processo pode demorar um pouco") lista_fronteiras = init(img_sem_ruido) #encontrar as bordas recorta_imagem(lista_fronteiras, img_sem_ruido, imagem, name_img) # recortar as folhas e salvar em disco (salvar a borda e a folha colorida) print("Analisando a textura das folhas encontradas") index_sub_folha = 1 while True: try: media, variancia, uniformidade, entropia = analise_textura(name_img, index_sub_folha) perimetro = len(lista_fronteiras[index_sub_folha-1]) incrementar_planilha(planilha, name_img, index_sub_folha, media, variancia, uniformidade, entropia, perimetro) index_sub_folha += 1 except: print("Fim da análise de textura para todas as folhas encontradas no arquivo: ", name_img) break img_number += 1 except: print("Acabou :) EBAA!") break if __name__ == "__main__": main()
turn(i,j)
conditional_block
teste.py
import numpy as np import cv2 from scipy import ndimage import math import csv BRANCO = 255 vizinhos = [[0,0],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1]] #verifica se o ponto pertence a uma fronteira def bool_nas_Fronteiras(ponto, listaDeFronteiras): for f in listaDeFronteiras: if boolPontoNaBorda(ponto, f): return True return False #retorna a posição de um pixel branco def encontrar_prox_branco(ponto, img): i, j = ponto row, col = img.shape while(i<row): while (j<col): if img[i,j] >= BRANCO: return(i,j) j+=1 j=0 i+=1 return (i-1,j) #retorna o proximo ponto diferente de branco e que não esta na lista de fronteiras def find_next_point(img, last_pixel, listaDeFronteiras): i, j = last_pixel row, col = img.shape i+=1 while(i<row): while (j<col): if img[i,j] < BRANCO and img[i, j-1] >= BRANCO: if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto return (i,j) else:#percorre a imagem ate achar um branco ponto_branco = encontrar_prox_branco((i,j), img) i=ponto_branco[0] j=ponto_branco[1] continue j+=1 j=0 i+=1 return 0 def boolPontoNaBorda(ponto, fronteira): return ponto in fronteira #encontrou o primeiro pronto da lista de fronteira #encontra o primeiro pixel diferente de branco def find_no_white(img): row, col = img.shape for i in range(row): for j in range(col): if img[i,j] < BRANCO: return (i,j)#retorna a posição do pixel #retorna a posição do array vizinhos def obterVizinhoID(x, y): for i in range(9): if(x == vizinhos[i][0] and y == vizinhos[i][1]): return i #a partir de um pixel inicial percorre a borda da folha def seguidorDeFronteira(img, first_pixel, i): row, col = img.shape fronteira=[] fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira x = 0 y = 1 #intuito de deixar o código mais legível b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y c_0 = [0, -1] anterior_b0 = [0, 0] cont = 1 contador_de_vizinhos = 0 find_init_border = True contador=0 while(find_init_border): indexVizinho=obterVizinhoID(c_0[x], c_0[y]) while(True): if(indexVizinho == 8):#zerar o clock indexVizinho = 0 proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO b_0 = [proxB_0[x], proxB_0[y]] check = (b_0[x],b_0[y]) if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira find_init_border = False break else: fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]] contador_de_vizinhos = 0 contador+=1 if proxB_0[x] > row: #para quando sair da imagem return False, (0,0) break contador_de_vizinhos +=1 if contador_de_vizinhos == 9: #para quando estiver um loop infinito return False, (0,0) cont = 0 anterior_b0 = [proxB_0[x], proxB_0[y]] indexVizinho += 1 #incrementa o vizinho tamanho = len(fronteira) if tamanho>50 and tamanho<25000: #tratamento da imagem 13 return True, fronteira return False, (0,0) def grayscale(img): row, col, bpp = np.shape(img) img_gray = [] for i in range(0,row): for j in range(0,col): b = int(img[i][j][0]) g = int(img[i][j][1]) r = int(img[i][j][2]) pixel = int((b+g+r) / 3) img_gray.append(pixel) return img_gray def remove_ruidos(imagem): img = imagem.astype('float') img = img[:,:,0] # convert to 2D array gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza _,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario img = cv2.medianBlur(img, 5) # remove o ruido return img #inicio do algoritmo seguidor de fronteiras def init(img):
listaDeFronteiras=[] first_no_white_pixel = find_no_white(img) next_pixel = first_no_white_pixel i=0 while(next_pixel!=0): try: is_fronteira, fronteira = seguidorDeFronteira(img, next_pixel, i) if is_fronteira: #caso seja uma fronteira valida listaDeFronteiras.append(fronteira) last_pixel = next_pixel next_pixel = find_next_point(img, last_pixel, listaDeFronteiras) except Exception as e: print(e) i+=1 #este tratamento funciona devido a imagem 13 for front in listaDeFronteiras: if len(front) > 19000: listaDeFronteiras.remove(front) print("NUMERO DE FOLHAS ENCONTRADAS:") print(len(listaDeFronteiras)) return listaDeFronteiras #retorna a altura, largura, menor linha e menor coluna def encontra_dimensoes(fronteira): x = 0 y = 1 list_y = [cord_y[y] for cord_y in fronteira] list_x = [cord_x[x] for cord_x in fronteira] x_menor = list_x[0] #pega a primeira posicao x_maior = max(list_x) y_menor = min(list_y) y_maior = max(list_y) #+3 serve para adicionar uma borda branca return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor #cria a imagem da fronteira e retorna uma imagem com a mascara def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img): row, col, bpp = img_borda.shape img_borda_binaria = np.zeros((row, col)) for pixel in fronteira: #transalada os pixeis nova_coordenada_x = (int(pixel[0])-menor_x)+1 nova_coordenada_y = (int(pixel[1])-menor_y)+1 img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0 img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0 #criando imagem binaria img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1 nome_imagem = name_img + '-' + str(index) +"-P"+ ".png" cv2.imwrite(nome_imagem, img_borda) img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int) return img_borda_binaria def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img): row, col, bpp = np.shape(imagem_branca) for i in range(row): for j in range(col): if img_borda_binaria[i][j] == 1: nova_coordenada_x = i+menor_x+1 nova_coordenada_y = j+menor_y+1 imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0] imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1] imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2] nome_imagem = name_img + '-' + str(index) + ".png" cv2.imwrite(nome_imagem, imagem_branca) return imagem_branca def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img): index = 1 for fronteira in lista_fronteiras: row, col, menor_x, menor_y = encontra_dimensoes(fronteira) #salavando a borda imagem_branca = np.ones((row, col, 3)) * 255 img_borda_binaria = criar_imagem_borda(imagem_branca, fronteira, menor_x, menor_y, index, name_img) #salvando a folha criar_imagem_unica_folha_colorida(imagem_sem_ruido, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img) index += 1 def valor_medio(histograma, lista_probabilidade): media = 0 j = 0 for i in histograma: media += i * lista_probabilidade[j] j += 1 return media def pixeis_coloridos(histograma): total = 0 for i in histograma: total += histograma[i] return total def probabilidade_de_cada_cor(histograma): lista_probabilidade = [] total_pixeis_coloridos = pixeis_coloridos(histograma) for i in histograma: probabilidade = histograma[i] / total_pixeis_coloridos lista_probabilidade.append(probabilidade) return lista_probabilidade def obter_histograma(imagem): histograma = {} img_gray = grayscale(imagem) #converte para tons de cinza arrendondando o valor for cor in img_gray: if cor != BRANCO: if cor in histograma.keys(): histograma[cor] += 1 else: histograma[cor] = 1 return histograma #função que retorna a media, variancia, uniformidade, entropia de cada folha def analise_textura(name_img, img_number): name_img = name_img + '-' + str(img_number) + ".png" imagem = cv2.imread(name_img) histograma = obter_histograma(imagem) probabilidade = probabilidade_de_cada_cor(histograma) media = valor_medio(histograma, probabilidade) j = 0 variancia = uniformidade = entropia = 0 for i in histograma: variancia += (((i-media)**2) * probabilidade[j]) uniformidade += (probabilidade[j] ** 2) entropia += (probabilidade[j] * np.log2(probabilidade[j])) * -1 j += 1 return media, variancia, uniformidade, entropia #realiza o tratamento do nome da imagem 1 -> Teste01 retorna o nome e a imagem do disco def pegar_nome(img_number): name_img = 'Folhas/Teste' if(img_number < 10): name_img = name_img + '0' name_img = name_img + str(img_number) + '.png' imagem = cv2.imread(name_img) name_img = name_img.split(".")[0] return imagem, name_img #cria a planilha .csv e adiciona os cabeçalhos def criar_planilha(): planilha = csv.writer(open("SAIDAS.csv", "w")) planilha.writerow(["ID imagem", "ID folha", "Media", "Variancia", "Uniformidade", "Entropia", "Perimetro"]) return planilha #escreve na planilha os dados obtidos de cada folha def incrementar_planilha(planilha, id_img, id_folha, media, variancia, uniformidade, entropia, perimetro): id_img = id_img.removeprefix('Folhas/') planilha.writerow([id_img, id_folha, media, variancia, uniformidade, entropia, perimetro]) #função principal do código qual chama as funções de execução def main(): print("Bem Vindo ao Trabalho de PID") img_number = 1 planilha = criar_planilha() while(True): try: imagem, name_img = pegar_nome(img_number) img_sem_ruido = remove_ruidos(imagem) lista_fronteiras = [] print("Encontrando todas as bordas de: ", name_img) print(" Este processo pode demorar um pouco") lista_fronteiras = init(img_sem_ruido) #encontrar as bordas recorta_imagem(lista_fronteiras, img_sem_ruido, imagem, name_img) # recortar as folhas e salvar em disco (salvar a borda e a folha colorida) print("Analisando a textura das folhas encontradas") index_sub_folha = 1 while True: try: media, variancia, uniformidade, entropia = analise_textura(name_img, index_sub_folha) perimetro = len(lista_fronteiras[index_sub_folha-1]) incrementar_planilha(planilha, name_img, index_sub_folha, media, variancia, uniformidade, entropia, perimetro) index_sub_folha += 1 except: print("Fim da análise de textura para todas as folhas encontradas no arquivo: ", name_img) break img_number += 1 except: print("Acabou :) EBAA!") break if __name__ == "__main__": main()
identifier_name
ekhoshim.py
#!/usr/bin/python # # See README.md for program description! import sys import os import tempfile import argparse import re import csv import inspect from pycparser import parse_file, c_parser, c_generator, c_ast lst = [] class Record(): """ A branch point in a program that will probably be annotated later. Stores line number, file name, and node type (if, elseif, etc.) """ next_id = 0 def __init__(self, line, file, name, funcName=None, funcList=None): self.line = line self.file = file self.name = name self.funcName = funcName self.funcList = funcList self.id = self.__class__._get_id() @classmethod def _get_id(cls): i = cls.next_id cls.next_id += 1 return i @classmethod def final_id(cls): return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs def __str__(self): return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList) class DefaultGenerator(c_generator.CGenerator): """ A C code generator that turns an Abstract Syntax Tree (AST) into an annotated version of the same file. Extend this class to change the contents of the debug lines. """
ELSE_HELPER = "0xDEADFAAB && 0xFEEDBEEF" NAME_TABLE = { "if": c_ast.If, "else": "else", "dowhile": c_ast.DoWhile, "for": c_ast.For, "funcdef": c_ast.FuncDef, "while": c_ast.While, "case": c_ast.Case, "default": c_ast.Default } def __init__(self, track): super(DefaultGenerator, self).__init__() self._current_record = None self._insert = False self._tracked = self._pick_trackers(track) self.records = [] def _pick_trackers(self,track): if "all" in track: return list(self.NAME_TABLE.values()) return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ] def preprocess(self, input_lines): lines = self._else_to_elseif(input_lines) return lines def _else_to_elseif(self, input_lines): content = "".join(input_lines) content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content) input_lines = content.splitlines(True) return input_lines def visit(self, node): if type(node) in self._tracked: self._current_record = self._record_from_node(node) self._insert = True method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def _common_visit(self, node): d = None if self._insert: d = self._build_tracking_line() self.records.append(self._current_record) s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node) if d is not None: s = self._shim_line(s, d) return s def _pick_tracking_statement(self, record): r = record #return "{} at {} in {}".format(r.name, r.line, r.file) return "{}".format(r.id) def _wrap_tracking_statement(self, statement): #return 'mspsim_printf("{}\\n");'.format(statement) return 'send_id({});'.format(statement) def _build_tracking_line(self): statement = self._pick_tracking_statement(self._current_record) s = ' ' * self.indent_level + self._wrap_tracking_statement(statement) self.insert = False return s def _shim_line(self, original, shim, n = 1): s = original.split('\n') if len(s) < n: return original s.insert(n, ' ' + shim) return '\n'.join(s) def visit_Compound(self, n): return self._common_visit(n) def visit_Case(self, n): return self._common_visit(n) def visit_Default(self, n): return self._common_visit(n) def visit_If(self, n): s = "" if n.cond: cond = self.visit(n.cond) if n.cond and cond == self.ELSE_HELPER: if "else" in self._tracked: self._insert = True self._current_record.name = "else" else: s = 'if (' if n.cond: s += cond s += ')\n' if c_ast.If not in self._tracked: self._insert = False s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def _create_child_tree(self, node): global lst #print "node is " + str(node.show()) my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass)) for (child_name, child) in node.children(): if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf": #print "\tChild: " + str(child.name.name) lst.append(child.name.name) elif isinstance(child, my_module_classes): self._create_child_tree(child) def _record_from_node(self, node): global lst c = node.coord funcName = None childlist = [] match = { c_ast.If: "if", c_ast.DoWhile: "dowhile", c_ast.For: "for", c_ast.FuncDef: "funcdef", c_ast.While: "while", c_ast.Case: "case", c_ast.Default: "default", } name = match[type(node)] if isinstance(node, c_ast.FuncDef): funcName = node.decl.name lst = [] self._create_child_tree(node) #if len(lst) > 0: # print "Parent function " + str(funcName) # print lst return Record(c.line, c.file, name, funcName, lst) class IdGenerator(DefaultGenerator): def _pick_tracking_statement(self, record): return "{}".format(record.id) class PrintGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'coverage("{}\\n");'.format(statement) class SerialGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'serial("{}\\n");'.format(statement) def _extract_directives(input_lines): extract = ['#include', '#ifdef', '#ifndef', '#endif'] code_lines = [] directive_lines = [] for line in input_lines: if any(word in line.lower() for word in extract): directive_lines.append(line.rstrip()) code_lines.insert(0, '\n') else: code_lines.append(line) return (code_lines, directive_lines) def generate(input_lines, track=None, generator_class=DefaultGenerator): if track is None: track = ["all"] generator = (generator_class)(track) input_lines = generator.preprocess(input_lines) code_lines, directive_lines = _extract_directives(input_lines) temp_file = tempfile.mkstemp()[1] with open(temp_file, 'w') as t: t.writelines(code_lines) ast = parse_file(temp_file, use_cpp=True, cpp_args=r'-Iutils/fake_libc_include') os.remove(temp_file) output_lines = [] output_lines.extend(directive_lines) output_lines.append('') output_lines.extend(generator.visit(ast).splitlines()) return (output_lines, generator.records) def lines_from_file(input_path): if input_path == '-': input_lines = sys.stdin.readlines() else: with open(input_path, 'r') as f: input_lines = f.readlines() return input_lines def write_to_file(output, output_path): if output_path == '-': print(output) elif output_path == "+": sys.stderr.write(output) else: with open(output_path, 'w') as f: f.write(output) def dump_record_index(records, record_path): if record_path == "-": csvfile = sys.stdout elif record_path == "+": csvfile = sys.stderr else: csvfile = open(record_path, 'w') writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) writer.writerow(["ID", "AST Node Type", "Line Number", "File", "Function Name", "Dependencies"]) for r in records: writer.writerow([r.id, r.name, r.line, r.file, r.funcName, r.funcList]) if record_path not in ("-", "+"): csvfile.close() def generate_from_file(input_path, output_path, record_path, track=None, generator_class=DefaultGenerator): input_lines = lines_from_file(input_path) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) write_to_file(output, args.outputfile) dump_record_index(records, record_path) def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator): output_list = [] records_list = [] for i in range(0, number_of_files): input_lines = lines_from_file(paths[i * 2]) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) for record in records: records_list.append(record) output_list.append(output) dump_record_index(records_list, paths[i * 2 + 2]) for j in range(0, len(output_list)): output_list[j] = output_list[j].replace("int main(void)\n{\n", "int main (void)\n{\n\tmain_start(" + str(Record.final_id()) + ");\n") write_to_file(output_list[j], paths[j * 2 + 1]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Ecko Shim: insert debug lines into C code at branching structures (like in loops and ifs). Warning: preprocessor directives EXCEPT for #include, #ifdef, #ifndef, and #endif will cause the program to crash. The other directives will ALL be moved to the top of the file.") parser.add_argument("--track", nargs='+', default='all', choices=["all", "if", "else", "dowhile", "for", "funcdef", "while", "case", "default"], metavar="tracking_choice", help="Provide any subset of {all, else, dowhile, for, funcdef, while, case, default}, e.g. '--track if else for'. The default is 'all'.") parser.add_argument("-n", type=int, default=1, help="Number of files to be converted:") parser.add_argument("files", help="List of <C input file> <C output file>, followed by a single <Record CSV file path>; - for stdin", nargs="+") #parser.add_argument("outputfile", help="C output file; - for stdout; + for stderr", nargs='+') #parser.add_argument("recordfile", help="Record CSV file path; - for stdout, + for stderr", nargs='+') parser.add_argument("--generator", choices=["print", "serial", "default"], default="default", help="Generator to use; print inserts print statements and serial does serial stuff. default for debugging.") args = parser.parse_args() classes = { "default": DefaultGenerator, "print": PrintGenerator, "serial": SerialGenerator, } generator_class = classes[args.generator] generate_from_multiple_files(args.n, args.files, args.track, generator_class) #generate_from_file(args.n, args.inputfile, args.outputfile, args.recordfile, args.track, generator_class) print "Total number of debug statements = " + str(Record.final_id())
random_line_split
ekhoshim.py
#!/usr/bin/python # # See README.md for program description! import sys import os import tempfile import argparse import re import csv import inspect from pycparser import parse_file, c_parser, c_generator, c_ast lst = [] class Record(): """ A branch point in a program that will probably be annotated later. Stores line number, file name, and node type (if, elseif, etc.) """ next_id = 0 def __init__(self, line, file, name, funcName=None, funcList=None):
@classmethod def _get_id(cls): i = cls.next_id cls.next_id += 1 return i @classmethod def final_id(cls): return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs def __str__(self): return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList) class DefaultGenerator(c_generator.CGenerator): """ A C code generator that turns an Abstract Syntax Tree (AST) into an annotated version of the same file. Extend this class to change the contents of the debug lines. """ ELSE_HELPER = "0xDEADFAAB && 0xFEEDBEEF" NAME_TABLE = { "if": c_ast.If, "else": "else", "dowhile": c_ast.DoWhile, "for": c_ast.For, "funcdef": c_ast.FuncDef, "while": c_ast.While, "case": c_ast.Case, "default": c_ast.Default } def __init__(self, track): super(DefaultGenerator, self).__init__() self._current_record = None self._insert = False self._tracked = self._pick_trackers(track) self.records = [] def _pick_trackers(self,track): if "all" in track: return list(self.NAME_TABLE.values()) return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ] def preprocess(self, input_lines): lines = self._else_to_elseif(input_lines) return lines def _else_to_elseif(self, input_lines): content = "".join(input_lines) content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content) input_lines = content.splitlines(True) return input_lines def visit(self, node): if type(node) in self._tracked: self._current_record = self._record_from_node(node) self._insert = True method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def _common_visit(self, node): d = None if self._insert: d = self._build_tracking_line() self.records.append(self._current_record) s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node) if d is not None: s = self._shim_line(s, d) return s def _pick_tracking_statement(self, record): r = record #return "{} at {} in {}".format(r.name, r.line, r.file) return "{}".format(r.id) def _wrap_tracking_statement(self, statement): #return 'mspsim_printf("{}\\n");'.format(statement) return 'send_id({});'.format(statement) def _build_tracking_line(self): statement = self._pick_tracking_statement(self._current_record) s = ' ' * self.indent_level + self._wrap_tracking_statement(statement) self.insert = False return s def _shim_line(self, original, shim, n = 1): s = original.split('\n') if len(s) < n: return original s.insert(n, ' ' + shim) return '\n'.join(s) def visit_Compound(self, n): return self._common_visit(n) def visit_Case(self, n): return self._common_visit(n) def visit_Default(self, n): return self._common_visit(n) def visit_If(self, n): s = "" if n.cond: cond = self.visit(n.cond) if n.cond and cond == self.ELSE_HELPER: if "else" in self._tracked: self._insert = True self._current_record.name = "else" else: s = 'if (' if n.cond: s += cond s += ')\n' if c_ast.If not in self._tracked: self._insert = False s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def _create_child_tree(self, node): global lst #print "node is " + str(node.show()) my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass)) for (child_name, child) in node.children(): if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf": #print "\tChild: " + str(child.name.name) lst.append(child.name.name) elif isinstance(child, my_module_classes): self._create_child_tree(child) def _record_from_node(self, node): global lst c = node.coord funcName = None childlist = [] match = { c_ast.If: "if", c_ast.DoWhile: "dowhile", c_ast.For: "for", c_ast.FuncDef: "funcdef", c_ast.While: "while", c_ast.Case: "case", c_ast.Default: "default", } name = match[type(node)] if isinstance(node, c_ast.FuncDef): funcName = node.decl.name lst = [] self._create_child_tree(node) #if len(lst) > 0: # print "Parent function " + str(funcName) # print lst return Record(c.line, c.file, name, funcName, lst) class IdGenerator(DefaultGenerator): def _pick_tracking_statement(self, record): return "{}".format(record.id) class PrintGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'coverage("{}\\n");'.format(statement) class SerialGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'serial("{}\\n");'.format(statement) def _extract_directives(input_lines): extract = ['#include', '#ifdef', '#ifndef', '#endif'] code_lines = [] directive_lines = [] for line in input_lines: if any(word in line.lower() for word in extract): directive_lines.append(line.rstrip()) code_lines.insert(0, '\n') else: code_lines.append(line) return (code_lines, directive_lines) def generate(input_lines, track=None, generator_class=DefaultGenerator): if track is None: track = ["all"] generator = (generator_class)(track) input_lines = generator.preprocess(input_lines) code_lines, directive_lines = _extract_directives(input_lines) temp_file = tempfile.mkstemp()[1] with open(temp_file, 'w') as t: t.writelines(code_lines) ast = parse_file(temp_file, use_cpp=True, cpp_args=r'-Iutils/fake_libc_include') os.remove(temp_file) output_lines = [] output_lines.extend(directive_lines) output_lines.append('') output_lines.extend(generator.visit(ast).splitlines()) return (output_lines, generator.records) def lines_from_file(input_path): if input_path == '-': input_lines = sys.stdin.readlines() else: with open(input_path, 'r') as f: input_lines = f.readlines() return input_lines def write_to_file(output, output_path): if output_path == '-': print(output) elif output_path == "+": sys.stderr.write(output) else: with open(output_path, 'w') as f: f.write(output) def dump_record_index(records, record_path): if record_path == "-": csvfile = sys.stdout elif record_path == "+": csvfile = sys.stderr else: csvfile = open(record_path, 'w') writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) writer.writerow(["ID", "AST Node Type", "Line Number", "File", "Function Name", "Dependencies"]) for r in records: writer.writerow([r.id, r.name, r.line, r.file, r.funcName, r.funcList]) if record_path not in ("-", "+"): csvfile.close() def generate_from_file(input_path, output_path, record_path, track=None, generator_class=DefaultGenerator): input_lines = lines_from_file(input_path) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) write_to_file(output, args.outputfile) dump_record_index(records, record_path) def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator): output_list = [] records_list = [] for i in range(0, number_of_files): input_lines = lines_from_file(paths[i * 2]) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) for record in records: records_list.append(record) output_list.append(output) dump_record_index(records_list, paths[i * 2 + 2]) for j in range(0, len(output_list)): output_list[j] = output_list[j].replace("int main(void)\n{\n", "int main (void)\n{\n\tmain_start(" + str(Record.final_id()) + ");\n") write_to_file(output_list[j], paths[j * 2 + 1]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Ecko Shim: insert debug lines into C code at branching structures (like in loops and ifs). Warning: preprocessor directives EXCEPT for #include, #ifdef, #ifndef, and #endif will cause the program to crash. The other directives will ALL be moved to the top of the file.") parser.add_argument("--track", nargs='+', default='all', choices=["all", "if", "else", "dowhile", "for", "funcdef", "while", "case", "default"], metavar="tracking_choice", help="Provide any subset of {all, else, dowhile, for, funcdef, while, case, default}, e.g. '--track if else for'. The default is 'all'.") parser.add_argument("-n", type=int, default=1, help="Number of files to be converted:") parser.add_argument("files", help="List of <C input file> <C output file>, followed by a single <Record CSV file path>; - for stdin", nargs="+") #parser.add_argument("outputfile", help="C output file; - for stdout; + for stderr", nargs='+') #parser.add_argument("recordfile", help="Record CSV file path; - for stdout, + for stderr", nargs='+') parser.add_argument("--generator", choices=["print", "serial", "default"], default="default", help="Generator to use; print inserts print statements and serial does serial stuff. default for debugging.") args = parser.parse_args() classes = { "default": DefaultGenerator, "print": PrintGenerator, "serial": SerialGenerator, } generator_class = classes[args.generator] generate_from_multiple_files(args.n, args.files, args.track, generator_class) #generate_from_file(args.n, args.inputfile, args.outputfile, args.recordfile, args.track, generator_class) print "Total number of debug statements = " + str(Record.final_id())
self.line = line self.file = file self.name = name self.funcName = funcName self.funcList = funcList self.id = self.__class__._get_id()
identifier_body
ekhoshim.py
#!/usr/bin/python # # See README.md for program description! import sys import os import tempfile import argparse import re import csv import inspect from pycparser import parse_file, c_parser, c_generator, c_ast lst = [] class Record(): """ A branch point in a program that will probably be annotated later. Stores line number, file name, and node type (if, elseif, etc.) """ next_id = 0 def __init__(self, line, file, name, funcName=None, funcList=None): self.line = line self.file = file self.name = name self.funcName = funcName self.funcList = funcList self.id = self.__class__._get_id() @classmethod def _get_id(cls): i = cls.next_id cls.next_id += 1 return i @classmethod def final_id(cls): return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs def __str__(self): return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList) class DefaultGenerator(c_generator.CGenerator): """ A C code generator that turns an Abstract Syntax Tree (AST) into an annotated version of the same file. Extend this class to change the contents of the debug lines. """ ELSE_HELPER = "0xDEADFAAB && 0xFEEDBEEF" NAME_TABLE = { "if": c_ast.If, "else": "else", "dowhile": c_ast.DoWhile, "for": c_ast.For, "funcdef": c_ast.FuncDef, "while": c_ast.While, "case": c_ast.Case, "default": c_ast.Default } def __init__(self, track): super(DefaultGenerator, self).__init__() self._current_record = None self._insert = False self._tracked = self._pick_trackers(track) self.records = [] def _pick_trackers(self,track): if "all" in track: return list(self.NAME_TABLE.values()) return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ] def preprocess(self, input_lines): lines = self._else_to_elseif(input_lines) return lines def _else_to_elseif(self, input_lines): content = "".join(input_lines) content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content) input_lines = content.splitlines(True) return input_lines def visit(self, node): if type(node) in self._tracked: self._current_record = self._record_from_node(node) self._insert = True method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def _common_visit(self, node): d = None if self._insert: d = self._build_tracking_line() self.records.append(self._current_record) s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node) if d is not None: s = self._shim_line(s, d) return s def _pick_tracking_statement(self, record): r = record #return "{} at {} in {}".format(r.name, r.line, r.file) return "{}".format(r.id) def _wrap_tracking_statement(self, statement): #return 'mspsim_printf("{}\\n");'.format(statement) return 'send_id({});'.format(statement) def _build_tracking_line(self): statement = self._pick_tracking_statement(self._current_record) s = ' ' * self.indent_level + self._wrap_tracking_statement(statement) self.insert = False return s def _shim_line(self, original, shim, n = 1): s = original.split('\n') if len(s) < n: return original s.insert(n, ' ' + shim) return '\n'.join(s) def visit_Compound(self, n): return self._common_visit(n) def visit_Case(self, n): return self._common_visit(n) def visit_Default(self, n): return self._common_visit(n) def visit_If(self, n): s = "" if n.cond: cond = self.visit(n.cond) if n.cond and cond == self.ELSE_HELPER: if "else" in self._tracked: self._insert = True self._current_record.name = "else" else: s = 'if (' if n.cond: s += cond s += ')\n' if c_ast.If not in self._tracked: self._insert = False s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def _create_child_tree(self, node): global lst #print "node is " + str(node.show()) my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass)) for (child_name, child) in node.children(): if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf": #print "\tChild: " + str(child.name.name) lst.append(child.name.name) elif isinstance(child, my_module_classes): self._create_child_tree(child) def _record_from_node(self, node): global lst c = node.coord funcName = None childlist = [] match = { c_ast.If: "if", c_ast.DoWhile: "dowhile", c_ast.For: "for", c_ast.FuncDef: "funcdef", c_ast.While: "while", c_ast.Case: "case", c_ast.Default: "default", } name = match[type(node)] if isinstance(node, c_ast.FuncDef): funcName = node.decl.name lst = [] self._create_child_tree(node) #if len(lst) > 0: # print "Parent function " + str(funcName) # print lst return Record(c.line, c.file, name, funcName, lst) class IdGenerator(DefaultGenerator): def _pick_tracking_statement(self, record): return "{}".format(record.id) class PrintGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'coverage("{}\\n");'.format(statement) class SerialGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'serial("{}\\n");'.format(statement) def _extract_directives(input_lines): extract = ['#include', '#ifdef', '#ifndef', '#endif'] code_lines = [] directive_lines = [] for line in input_lines: if any(word in line.lower() for word in extract): directive_lines.append(line.rstrip()) code_lines.insert(0, '\n') else: code_lines.append(line) return (code_lines, directive_lines) def generate(input_lines, track=None, generator_class=DefaultGenerator): if track is None: track = ["all"] generator = (generator_class)(track) input_lines = generator.preprocess(input_lines) code_lines, directive_lines = _extract_directives(input_lines) temp_file = tempfile.mkstemp()[1] with open(temp_file, 'w') as t: t.writelines(code_lines) ast = parse_file(temp_file, use_cpp=True, cpp_args=r'-Iutils/fake_libc_include') os.remove(temp_file) output_lines = [] output_lines.extend(directive_lines) output_lines.append('') output_lines.extend(generator.visit(ast).splitlines()) return (output_lines, generator.records) def lines_from_file(input_path): if input_path == '-': input_lines = sys.stdin.readlines() else: with open(input_path, 'r') as f: input_lines = f.readlines() return input_lines def write_to_file(output, output_path): if output_path == '-': print(output) elif output_path == "+": sys.stderr.write(output) else: with open(output_path, 'w') as f: f.write(output) def dump_record_index(records, record_path): if record_path == "-": csvfile = sys.stdout elif record_path == "+": csvfile = sys.stderr else:
writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) writer.writerow(["ID", "AST Node Type", "Line Number", "File", "Function Name", "Dependencies"]) for r in records: writer.writerow([r.id, r.name, r.line, r.file, r.funcName, r.funcList]) if record_path not in ("-", "+"): csvfile.close() def generate_from_file(input_path, output_path, record_path, track=None, generator_class=DefaultGenerator): input_lines = lines_from_file(input_path) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) write_to_file(output, args.outputfile) dump_record_index(records, record_path) def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator): output_list = [] records_list = [] for i in range(0, number_of_files): input_lines = lines_from_file(paths[i * 2]) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) for record in records: records_list.append(record) output_list.append(output) dump_record_index(records_list, paths[i * 2 + 2]) for j in range(0, len(output_list)): output_list[j] = output_list[j].replace("int main(void)\n{\n", "int main (void)\n{\n\tmain_start(" + str(Record.final_id()) + ");\n") write_to_file(output_list[j], paths[j * 2 + 1]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Ecko Shim: insert debug lines into C code at branching structures (like in loops and ifs). Warning: preprocessor directives EXCEPT for #include, #ifdef, #ifndef, and #endif will cause the program to crash. The other directives will ALL be moved to the top of the file.") parser.add_argument("--track", nargs='+', default='all', choices=["all", "if", "else", "dowhile", "for", "funcdef", "while", "case", "default"], metavar="tracking_choice", help="Provide any subset of {all, else, dowhile, for, funcdef, while, case, default}, e.g. '--track if else for'. The default is 'all'.") parser.add_argument("-n", type=int, default=1, help="Number of files to be converted:") parser.add_argument("files", help="List of <C input file> <C output file>, followed by a single <Record CSV file path>; - for stdin", nargs="+") #parser.add_argument("outputfile", help="C output file; - for stdout; + for stderr", nargs='+') #parser.add_argument("recordfile", help="Record CSV file path; - for stdout, + for stderr", nargs='+') parser.add_argument("--generator", choices=["print", "serial", "default"], default="default", help="Generator to use; print inserts print statements and serial does serial stuff. default for debugging.") args = parser.parse_args() classes = { "default": DefaultGenerator, "print": PrintGenerator, "serial": SerialGenerator, } generator_class = classes[args.generator] generate_from_multiple_files(args.n, args.files, args.track, generator_class) #generate_from_file(args.n, args.inputfile, args.outputfile, args.recordfile, args.track, generator_class) print "Total number of debug statements = " + str(Record.final_id())
csvfile = open(record_path, 'w')
conditional_block
ekhoshim.py
#!/usr/bin/python # # See README.md for program description! import sys import os import tempfile import argparse import re import csv import inspect from pycparser import parse_file, c_parser, c_generator, c_ast lst = [] class Record(): """ A branch point in a program that will probably be annotated later. Stores line number, file name, and node type (if, elseif, etc.) """ next_id = 0 def __init__(self, line, file, name, funcName=None, funcList=None): self.line = line self.file = file self.name = name self.funcName = funcName self.funcList = funcList self.id = self.__class__._get_id() @classmethod def _get_id(cls): i = cls.next_id cls.next_id += 1 return i @classmethod def final_id(cls): return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs def __str__(self): return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList) class DefaultGenerator(c_generator.CGenerator): """ A C code generator that turns an Abstract Syntax Tree (AST) into an annotated version of the same file. Extend this class to change the contents of the debug lines. """ ELSE_HELPER = "0xDEADFAAB && 0xFEEDBEEF" NAME_TABLE = { "if": c_ast.If, "else": "else", "dowhile": c_ast.DoWhile, "for": c_ast.For, "funcdef": c_ast.FuncDef, "while": c_ast.While, "case": c_ast.Case, "default": c_ast.Default } def __init__(self, track): super(DefaultGenerator, self).__init__() self._current_record = None self._insert = False self._tracked = self._pick_trackers(track) self.records = [] def _pick_trackers(self,track): if "all" in track: return list(self.NAME_TABLE.values()) return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ] def preprocess(self, input_lines): lines = self._else_to_elseif(input_lines) return lines def _else_to_elseif(self, input_lines): content = "".join(input_lines) content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content) input_lines = content.splitlines(True) return input_lines def visit(self, node): if type(node) in self._tracked: self._current_record = self._record_from_node(node) self._insert = True method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def _common_visit(self, node): d = None if self._insert: d = self._build_tracking_line() self.records.append(self._current_record) s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node) if d is not None: s = self._shim_line(s, d) return s def _pick_tracking_statement(self, record): r = record #return "{} at {} in {}".format(r.name, r.line, r.file) return "{}".format(r.id) def _wrap_tracking_statement(self, statement): #return 'mspsim_printf("{}\\n");'.format(statement) return 'send_id({});'.format(statement) def _build_tracking_line(self): statement = self._pick_tracking_statement(self._current_record) s = ' ' * self.indent_level + self._wrap_tracking_statement(statement) self.insert = False return s def _shim_line(self, original, shim, n = 1): s = original.split('\n') if len(s) < n: return original s.insert(n, ' ' + shim) return '\n'.join(s) def visit_Compound(self, n): return self._common_visit(n) def visit_Case(self, n): return self._common_visit(n) def visit_Default(self, n): return self._common_visit(n) def visit_If(self, n): s = "" if n.cond: cond = self.visit(n.cond) if n.cond and cond == self.ELSE_HELPER: if "else" in self._tracked: self._insert = True self._current_record.name = "else" else: s = 'if (' if n.cond: s += cond s += ')\n' if c_ast.If not in self._tracked: self._insert = False s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def _create_child_tree(self, node): global lst #print "node is " + str(node.show()) my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass)) for (child_name, child) in node.children(): if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf": #print "\tChild: " + str(child.name.name) lst.append(child.name.name) elif isinstance(child, my_module_classes): self._create_child_tree(child) def _record_from_node(self, node): global lst c = node.coord funcName = None childlist = [] match = { c_ast.If: "if", c_ast.DoWhile: "dowhile", c_ast.For: "for", c_ast.FuncDef: "funcdef", c_ast.While: "while", c_ast.Case: "case", c_ast.Default: "default", } name = match[type(node)] if isinstance(node, c_ast.FuncDef): funcName = node.decl.name lst = [] self._create_child_tree(node) #if len(lst) > 0: # print "Parent function " + str(funcName) # print lst return Record(c.line, c.file, name, funcName, lst) class IdGenerator(DefaultGenerator): def _pick_tracking_statement(self, record): return "{}".format(record.id) class PrintGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'coverage("{}\\n");'.format(statement) class SerialGenerator(IdGenerator): def _wrap_tracking_statement(self, statement): return 'serial("{}\\n");'.format(statement) def _extract_directives(input_lines): extract = ['#include', '#ifdef', '#ifndef', '#endif'] code_lines = [] directive_lines = [] for line in input_lines: if any(word in line.lower() for word in extract): directive_lines.append(line.rstrip()) code_lines.insert(0, '\n') else: code_lines.append(line) return (code_lines, directive_lines) def generate(input_lines, track=None, generator_class=DefaultGenerator): if track is None: track = ["all"] generator = (generator_class)(track) input_lines = generator.preprocess(input_lines) code_lines, directive_lines = _extract_directives(input_lines) temp_file = tempfile.mkstemp()[1] with open(temp_file, 'w') as t: t.writelines(code_lines) ast = parse_file(temp_file, use_cpp=True, cpp_args=r'-Iutils/fake_libc_include') os.remove(temp_file) output_lines = [] output_lines.extend(directive_lines) output_lines.append('') output_lines.extend(generator.visit(ast).splitlines()) return (output_lines, generator.records) def lines_from_file(input_path): if input_path == '-': input_lines = sys.stdin.readlines() else: with open(input_path, 'r') as f: input_lines = f.readlines() return input_lines def write_to_file(output, output_path): if output_path == '-': print(output) elif output_path == "+": sys.stderr.write(output) else: with open(output_path, 'w') as f: f.write(output) def dump_record_index(records, record_path): if record_path == "-": csvfile = sys.stdout elif record_path == "+": csvfile = sys.stderr else: csvfile = open(record_path, 'w') writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) writer.writerow(["ID", "AST Node Type", "Line Number", "File", "Function Name", "Dependencies"]) for r in records: writer.writerow([r.id, r.name, r.line, r.file, r.funcName, r.funcList]) if record_path not in ("-", "+"): csvfile.close() def
(input_path, output_path, record_path, track=None, generator_class=DefaultGenerator): input_lines = lines_from_file(input_path) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) write_to_file(output, args.outputfile) dump_record_index(records, record_path) def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator): output_list = [] records_list = [] for i in range(0, number_of_files): input_lines = lines_from_file(paths[i * 2]) output_lines, records = generate(input_lines, track, generator_class) output = "\n".join(output_lines) for record in records: records_list.append(record) output_list.append(output) dump_record_index(records_list, paths[i * 2 + 2]) for j in range(0, len(output_list)): output_list[j] = output_list[j].replace("int main(void)\n{\n", "int main (void)\n{\n\tmain_start(" + str(Record.final_id()) + ");\n") write_to_file(output_list[j], paths[j * 2 + 1]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Ecko Shim: insert debug lines into C code at branching structures (like in loops and ifs). Warning: preprocessor directives EXCEPT for #include, #ifdef, #ifndef, and #endif will cause the program to crash. The other directives will ALL be moved to the top of the file.") parser.add_argument("--track", nargs='+', default='all', choices=["all", "if", "else", "dowhile", "for", "funcdef", "while", "case", "default"], metavar="tracking_choice", help="Provide any subset of {all, else, dowhile, for, funcdef, while, case, default}, e.g. '--track if else for'. The default is 'all'.") parser.add_argument("-n", type=int, default=1, help="Number of files to be converted:") parser.add_argument("files", help="List of <C input file> <C output file>, followed by a single <Record CSV file path>; - for stdin", nargs="+") #parser.add_argument("outputfile", help="C output file; - for stdout; + for stderr", nargs='+') #parser.add_argument("recordfile", help="Record CSV file path; - for stdout, + for stderr", nargs='+') parser.add_argument("--generator", choices=["print", "serial", "default"], default="default", help="Generator to use; print inserts print statements and serial does serial stuff. default for debugging.") args = parser.parse_args() classes = { "default": DefaultGenerator, "print": PrintGenerator, "serial": SerialGenerator, } generator_class = classes[args.generator] generate_from_multiple_files(args.n, args.files, args.track, generator_class) #generate_from_file(args.n, args.inputfile, args.outputfile, args.recordfile, args.track, generator_class) print "Total number of debug statements = " + str(Record.final_id())
generate_from_file
identifier_name
listener.go
package eventlistener import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "time" "github.com/pkg/errors" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric-protos-go/ledger/rwset" "github.com/hyperledger/fabric-protos-go/msp" pb "github.com/hyperledger/fabric-protos-go/peer" "github.com/hyperledger/fabric-sdk-go/pkg/client/event" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) const ( // EventBlock type for block event EventBlock = "Block" // EventFiltered type for filtered block event EventFiltered = "Filtered Block" // EventChaincode type for chaincode event EventChaincode = "Chaincode" ) // cllientMap var clientMap = map[string]*event.Client{} // EventHandler defines action on event data type EventHandler func(data interface{}) // Listener caches event listener info type Listener struct { client *event.Client eventType string chaincodeID string eventFilter string handler EventHandler stopchan chan struct{} exitchan chan struct{} } // NewListener creates a lisenter instance func NewListener(spec *Spec, handler EventHandler) (*Listener, error) { client, err := getEventClient(spec) if err != nil { return nil, err } listener := Listener{ client: client, eventType: spec.EventType, chaincodeID: spec.ChaincodeID, eventFilter: spec.EventFilter, handler: handler, } return &listener, nil } // Start starts the event listener func (c *Listener) Start() error { switch c.eventType { case EventBlock: // register and wait for one block event registration, blkChan, err := c.client.RegisterBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register block event") } logger.Info("block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveBlockEvent(blkChan, c.handler, c.stopchan) }() case EventFiltered: // register and wait for one filtered block event registration, blkChan, err := c.client.RegisterFilteredBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register filtered block event") } logger.Info("filtered block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan) }() case EventChaincode: // register and wait for one chaincode event registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilter) if err != nil { return errors.Wrapf(err, "Failed to register chaincode event") } logger.Info("chaincode event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveChaincodeEvent(ccChan, c.handler, c.stopchan) }() default: logger.Infof("event type '%s' is not supported", c.eventType) } return nil } // Stop stops the event listener func (c *Listener) Stop() { logger.Info("Stop listener ...") close(c.stopchan) <-c.exitchan logger.Info("Listener stopped") } // Spec defines client for fabric events type Spec struct { Name string NetworkConfig []byte EntityMatchers []byte OrgName string UserName string ChannelID string EventType string ChaincodeID string EventFilter string } func clientID(spec *Spec) string { return fmt.Sprintf("%s.%s.%s.%t", spec.Name, spec.UserName, spec.OrgName, spec.EventType != EventFiltered) } // getEventClient returns cached event client or create a new event client if it does not exist func getEventClient(spec *Spec) (*event.Client, error) { cid := clientID(spec) client, ok := clientMap[cid] if ok && client != nil { return client, nil } // create new event client sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers)) if err != nil { return nil, errors.Wrapf(err, "Failed to create new SDK") } opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)} if spec.OrgName != "" { opts = append(opts, fabsdk.WithOrg(spec.OrgName)) } if spec.EventType == EventFiltered { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...)) } else { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents()) } if err != nil { clientMap[cid] = client } return client, err } func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) { for { var ccEvent *fab.CCEvent select { case ccEvent = <-ccChan: cce := unmarshalChaincodeEvent(ccEvent) handler(cce) case <-stopchan: logger.Info("Quit listener for chaincode event") return } } } func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail { ced := CCEventDetail{ BlockNumber: ccEvent.BlockNumber, SourceURL: ccEvent.SourceURL, TxID: ccEvent.TxID, ChaincodeID: ccEvent.ChaincodeID, EventName: ccEvent.EventName, Payload: string(ccEvent.Payload), } return &ced } func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.FilteredBlockEvent select { case blkEvent = <-blkChan: bed := unmarshalFilteredBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for filtered block event") return } } } func unmarshalFilteredBlockEvent(blkEvent *fab.FilteredBlockEvent) *BlockEventDetail { blk := blkEvent.FilteredBlock // blkjson, _ := json.Marshal(blk) // fmt.Println(string(blkjson)) bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blk.Number, Transactions: []*TransactionDetail{}, } for _, d := range blk.FilteredTransactions { td := TransactionDetail{ TxType: common.HeaderType_name[int32(d.Type)], TxID: d.Txid, ChannelID: blk.ChannelId, Actions: []*ActionDetail{}, } bed.Transactions = append(bed.Transactions, &td) actions := d.GetTransactionActions() if actions != nil { for _, ta := range actions.ChaincodeActions { ce := ta.GetChaincodeEvent() if ce != nil && ce.ChaincodeId != "" { action := ActionDetail{ Chaincode: &ChaincodeID{Name: ce.ChaincodeId}, Result: &ChaincodeResult{ Event: &ChaincodeEvent{ Name: ce.EventName, Payload: string(ce.Payload), }, }, } td.Actions = append(td.Actions, &action) } } } } return &bed } func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.BlockEvent select { case blkEvent = <-blkChan: bed := unmarshalBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for block event") return } } } func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail { bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blkEvent.Block.Header.Number, Transactions: []*TransactionDetail{}, } for _, d := range blkEvent.Block.Data.Data { txn, err := unmarshalTransaction(d) if err != nil { logger.Errorf("Error unmarshalling transaction: %+v", err) continue } else { bed.Transactions = append(bed.Transactions, txn) } } return &bed } func unmarshalTransaction(data []byte) (*TransactionDetail, error) { envelope, err := GetEnvelopeFromBlock(data) if err != nil { return nil, errors.Wrapf(err, "failed to get envelope") } payload, err := UnmarshalPayload(envelope.Payload) if err != nil { return nil, errors.Wrapf(err, "failed to get payload") } if payload.Header == nil { return nil, errors.Errorf("payload header is empty") }
if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal channel header") } td := TransactionDetail{ TxType: common.HeaderType_name[chdr.Type], TxID: chdr.TxId, TxTime: time.Unix(chdr.Timestamp.Seconds, int64(chdr.Timestamp.Nanos)).UTC().String(), ChannelID: chdr.ChannelId, Actions: []*ActionDetail{}, } // signature header shdr := &common.SignatureHeader{} if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil { logger.Errorf("failed to unmarshal signature header: %+v", err) } else { cid, err := unmarshalIdentity(shdr.Creator) if err != nil { logger.Errorf("failed to unmarshal creator identity: %+v", err) } else { td.CreatorIdentity = cid } } txn, err := UnmarshalTransaction(payload.Data) if err != nil { return &td, errors.Wrapf(err, "failed to get transaction") } for _, ta := range txn.Actions { act, err := unmarshalAction(ta.Payload) if err != nil { logger.Errorf("Error unmarshalling action: %+v", err) continue } else { td.Actions = append(td.Actions, act) } } return &td, nil } func unmarshalIdentity(data []byte) (*Identity, error) { cid := &msp.SerializedIdentity{} if err := proto.Unmarshal(data, cid); err != nil { return nil, err } id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)} // extract info from x509 certificate block, _ := pem.Decode(cid.IdBytes) if block == nil { logger.Info("creator certificate is empty") return &id, nil } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { logger.Errorf("failed to parse creator certificate: %+v", err) return &id, nil } id.Subject = cert.Subject.CommonName id.Issuer = cert.Issuer.CommonName return &id, nil } func unmarshalAction(data []byte) (*ActionDetail, error) { ccAction, err := UnmarshalChaincodeActionPayload(data) if err != nil { return nil, errors.Wrapf(err, "failed to get action payload") } // proposal payload proposalPayload, err := UnmarshalChaincodeProposalPayload(ccAction.ChaincodeProposalPayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal payload") } cis := &pb.ChaincodeInvocationSpec{} err = proto.Unmarshal(proposalPayload.Input, cis) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal chaincode input") } // chaincode spec ccID := ChaincodeID{ Type: pb.ChaincodeSpec_Type_name[int32(cis.ChaincodeSpec.Type)], Name: cis.ChaincodeSpec.ChaincodeId.Name, } // chaincode input args := cis.ChaincodeSpec.Input.Args ccInput := ChaincodeInput{ Function: string(args[0]), Args: []string{}, } if len(args) > 1 { for _, arg := range args[1:] { ccInput.Args = append(ccInput.Args, string(arg)) } } if proposalPayload.TransientMap != nil { tm := make(map[string]string) for k, v := range proposalPayload.TransientMap { tm[k] = string(v) } if tb, err := json.Marshal(tm); err != nil { logger.Errorf("failed to marshal transient map to JSON: %+v", err) } else { ccInput.TransientMap = string(tb) } } // action response payload prespPayload, err := UnmarshalProposalResponsePayload(ccAction.Action.ProposalResponsePayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal response payload") } cact, err := UnmarshalChaincodeAction(prespPayload.Extension) if err != nil { return nil, errors.Wrapf(err, "failed to get chaincode action") } if cact.Response == nil { return nil, errors.New("chaincode response is empty") } if cact.ChaincodeId != nil { ccID.Version = cact.ChaincodeId.Version } // chaincode response ccResult := ChaincodeResult{ Response: &ChaincodeResponse{ Status: cact.Response.Status, Message: cact.Response.Message, Payload: string(cact.Response.Payload), }, } action := ActionDetail{ Chaincode: &ccID, Input: &ccInput, Result: &ccResult, EndorserCount: len(ccAction.Action.Endorsements), } // chaincode result if cact.Results != nil { txrw := &rwset.TxReadWriteSet{} err := proto.Unmarshal(cact.Results, txrw) if err != nil { logger.Errorf("failed to unmarshal tx rwset: %+v", err) } else { ccResult.ReadWriteCount = len(txrw.NsRwset) } } // chaincode event if cact.Events != nil { if ccEvt, err := UnmarshalChaincodeEvents(cact.Events); err != nil { logger.Errorf("failed to get chaincode event: %+v", err) } else { ccResult.Event = &ChaincodeEvent{ Name: ccEvt.EventName, Payload: string(ccEvt.Payload), } } } return &action, nil } // CCEventDetail contains data in a chaincode event type CCEventDetail struct { BlockNumber uint64 `json:"block"` SourceURL string `json:"source,omitempty"` TxID string `json:"txId"` ChaincodeID string `json:"chaincode"` EventName string `json:"name"` Payload string `json:"payload"` } // BlockEventDetail contains data in a block event type BlockEventDetail struct { Number uint64 `json:"block"` SourceURL string `json:"source,omitempty"` Transactions []*TransactionDetail `json:"transactions"` } // TransactionDetail contains data in a transaction type TransactionDetail struct { TxType string `json:"type"` TxID string `json:"txId"` TxTime string `json:"txTime,omitempty"` ChannelID string `json:"channel"` CreatorIdentity *Identity `json:"creator,omitempty"` Actions []*ActionDetail `json:"actions,omitempty"` } // Identity contains creator's mspid and certificate type Identity struct { Mspid string `json:"mspid"` Subject string `json:"subject,omitempty"` Issuer string `json:"issuer,omitempty"` Cert string `json:"cert,omitempty"` } // ActionDetail contains data in a chaincode invocation type ActionDetail struct { Chaincode *ChaincodeID `json:"chaincode,omitempty"` Input *ChaincodeInput `json:"input,omitempty"` Result *ChaincodeResult `json:"result,omitempty"` EndorserCount int `json:"endorsers,omitempty"` } // ChaincodeID defines chaincode identity type ChaincodeID struct { Type string `json:"type,omitempty"` Name string `json:"name"` Version string `json:"version,omitempty"` } // ChaincodeInput defines input parameters of a chaincode invocation type ChaincodeInput struct { Function string `json:"function"` Args []string `json:"args,omitempty"` TransientMap string `json:"transient,omitempty"` } // ChaincodeResult defines result of a chaincode invocation type ChaincodeResult struct { ReadWriteCount int `json:"rwset,omitempty"` Response *ChaincodeResponse `json:"response,omitempty"` Event *ChaincodeEvent `json:"event,omitempty"` } // ChaincodeResponse defines response from a chaincode invocation type ChaincodeResponse struct { Status int32 `json:"status"` Message string `json:"message,omitempty"` Payload string `json:"payload,omitempty"` } // ChaincodeEvent defines event created by a chaincode invocation type ChaincodeEvent struct { Name string `json:"name"` Payload string `json:"payload,omitempty"` } func networkConfigProvider(networkConfig []byte, entityMatcherOverride []byte) core.ConfigProvider { configProvider := config.FromRaw(networkConfig, "yaml") if entityMatcherOverride != nil { return func() ([]core.ConfigBackend, error) { matcherProvider := config.FromRaw(entityMatcherOverride, "yaml") matcherBackends, err := matcherProvider() if err != nil { logger.Errorf("failed to parse entity matchers: %+v", err) // return the original config provider defined by configPath return configProvider() } currentBackends, err := configProvider() if err != nil { logger.Errorf("failed to parse network config: %+v", err) return nil, err } // return the combined config with matcher precedency return append(matcherBackends, currentBackends...), nil } } return configProvider }
// channel header chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)
random_line_split
listener.go
package eventlistener import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "time" "github.com/pkg/errors" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric-protos-go/ledger/rwset" "github.com/hyperledger/fabric-protos-go/msp" pb "github.com/hyperledger/fabric-protos-go/peer" "github.com/hyperledger/fabric-sdk-go/pkg/client/event" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) const ( // EventBlock type for block event EventBlock = "Block" // EventFiltered type for filtered block event EventFiltered = "Filtered Block" // EventChaincode type for chaincode event EventChaincode = "Chaincode" ) // cllientMap var clientMap = map[string]*event.Client{} // EventHandler defines action on event data type EventHandler func(data interface{}) // Listener caches event listener info type Listener struct { client *event.Client eventType string chaincodeID string eventFilter string handler EventHandler stopchan chan struct{} exitchan chan struct{} } // NewListener creates a lisenter instance func NewListener(spec *Spec, handler EventHandler) (*Listener, error) { client, err := getEventClient(spec) if err != nil { return nil, err } listener := Listener{ client: client, eventType: spec.EventType, chaincodeID: spec.ChaincodeID, eventFilter: spec.EventFilter, handler: handler, } return &listener, nil } // Start starts the event listener func (c *Listener) Start() error { switch c.eventType { case EventBlock: // register and wait for one block event registration, blkChan, err := c.client.RegisterBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register block event") } logger.Info("block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveBlockEvent(blkChan, c.handler, c.stopchan) }() case EventFiltered: // register and wait for one filtered block event registration, blkChan, err := c.client.RegisterFilteredBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register filtered block event") } logger.Info("filtered block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan) }() case EventChaincode: // register and wait for one chaincode event registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilter) if err != nil { return errors.Wrapf(err, "Failed to register chaincode event") } logger.Info("chaincode event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveChaincodeEvent(ccChan, c.handler, c.stopchan) }() default: logger.Infof("event type '%s' is not supported", c.eventType) } return nil } // Stop stops the event listener func (c *Listener) Stop() { logger.Info("Stop listener ...") close(c.stopchan) <-c.exitchan logger.Info("Listener stopped") } // Spec defines client for fabric events type Spec struct { Name string NetworkConfig []byte EntityMatchers []byte OrgName string UserName string ChannelID string EventType string ChaincodeID string EventFilter string } func clientID(spec *Spec) string { return fmt.Sprintf("%s.%s.%s.%t", spec.Name, spec.UserName, spec.OrgName, spec.EventType != EventFiltered) } // getEventClient returns cached event client or create a new event client if it does not exist func getEventClient(spec *Spec) (*event.Client, error) { cid := clientID(spec) client, ok := clientMap[cid] if ok && client != nil { return client, nil } // create new event client sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers)) if err != nil { return nil, errors.Wrapf(err, "Failed to create new SDK") } opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)} if spec.OrgName != "" { opts = append(opts, fabsdk.WithOrg(spec.OrgName)) } if spec.EventType == EventFiltered { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...)) } else { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents()) } if err != nil { clientMap[cid] = client } return client, err } func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) { for { var ccEvent *fab.CCEvent select { case ccEvent = <-ccChan: cce := unmarshalChaincodeEvent(ccEvent) handler(cce) case <-stopchan: logger.Info("Quit listener for chaincode event") return } } } func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail { ced := CCEventDetail{ BlockNumber: ccEvent.BlockNumber, SourceURL: ccEvent.SourceURL, TxID: ccEvent.TxID, ChaincodeID: ccEvent.ChaincodeID, EventName: ccEvent.EventName, Payload: string(ccEvent.Payload), } return &ced } func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.FilteredBlockEvent select { case blkEvent = <-blkChan: bed := unmarshalFilteredBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for filtered block event") return } } } func
(blkEvent *fab.FilteredBlockEvent) *BlockEventDetail { blk := blkEvent.FilteredBlock // blkjson, _ := json.Marshal(blk) // fmt.Println(string(blkjson)) bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blk.Number, Transactions: []*TransactionDetail{}, } for _, d := range blk.FilteredTransactions { td := TransactionDetail{ TxType: common.HeaderType_name[int32(d.Type)], TxID: d.Txid, ChannelID: blk.ChannelId, Actions: []*ActionDetail{}, } bed.Transactions = append(bed.Transactions, &td) actions := d.GetTransactionActions() if actions != nil { for _, ta := range actions.ChaincodeActions { ce := ta.GetChaincodeEvent() if ce != nil && ce.ChaincodeId != "" { action := ActionDetail{ Chaincode: &ChaincodeID{Name: ce.ChaincodeId}, Result: &ChaincodeResult{ Event: &ChaincodeEvent{ Name: ce.EventName, Payload: string(ce.Payload), }, }, } td.Actions = append(td.Actions, &action) } } } } return &bed } func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.BlockEvent select { case blkEvent = <-blkChan: bed := unmarshalBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for block event") return } } } func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail { bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blkEvent.Block.Header.Number, Transactions: []*TransactionDetail{}, } for _, d := range blkEvent.Block.Data.Data { txn, err := unmarshalTransaction(d) if err != nil { logger.Errorf("Error unmarshalling transaction: %+v", err) continue } else { bed.Transactions = append(bed.Transactions, txn) } } return &bed } func unmarshalTransaction(data []byte) (*TransactionDetail, error) { envelope, err := GetEnvelopeFromBlock(data) if err != nil { return nil, errors.Wrapf(err, "failed to get envelope") } payload, err := UnmarshalPayload(envelope.Payload) if err != nil { return nil, errors.Wrapf(err, "failed to get payload") } if payload.Header == nil { return nil, errors.Errorf("payload header is empty") } // channel header chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal channel header") } td := TransactionDetail{ TxType: common.HeaderType_name[chdr.Type], TxID: chdr.TxId, TxTime: time.Unix(chdr.Timestamp.Seconds, int64(chdr.Timestamp.Nanos)).UTC().String(), ChannelID: chdr.ChannelId, Actions: []*ActionDetail{}, } // signature header shdr := &common.SignatureHeader{} if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil { logger.Errorf("failed to unmarshal signature header: %+v", err) } else { cid, err := unmarshalIdentity(shdr.Creator) if err != nil { logger.Errorf("failed to unmarshal creator identity: %+v", err) } else { td.CreatorIdentity = cid } } txn, err := UnmarshalTransaction(payload.Data) if err != nil { return &td, errors.Wrapf(err, "failed to get transaction") } for _, ta := range txn.Actions { act, err := unmarshalAction(ta.Payload) if err != nil { logger.Errorf("Error unmarshalling action: %+v", err) continue } else { td.Actions = append(td.Actions, act) } } return &td, nil } func unmarshalIdentity(data []byte) (*Identity, error) { cid := &msp.SerializedIdentity{} if err := proto.Unmarshal(data, cid); err != nil { return nil, err } id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)} // extract info from x509 certificate block, _ := pem.Decode(cid.IdBytes) if block == nil { logger.Info("creator certificate is empty") return &id, nil } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { logger.Errorf("failed to parse creator certificate: %+v", err) return &id, nil } id.Subject = cert.Subject.CommonName id.Issuer = cert.Issuer.CommonName return &id, nil } func unmarshalAction(data []byte) (*ActionDetail, error) { ccAction, err := UnmarshalChaincodeActionPayload(data) if err != nil { return nil, errors.Wrapf(err, "failed to get action payload") } // proposal payload proposalPayload, err := UnmarshalChaincodeProposalPayload(ccAction.ChaincodeProposalPayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal payload") } cis := &pb.ChaincodeInvocationSpec{} err = proto.Unmarshal(proposalPayload.Input, cis) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal chaincode input") } // chaincode spec ccID := ChaincodeID{ Type: pb.ChaincodeSpec_Type_name[int32(cis.ChaincodeSpec.Type)], Name: cis.ChaincodeSpec.ChaincodeId.Name, } // chaincode input args := cis.ChaincodeSpec.Input.Args ccInput := ChaincodeInput{ Function: string(args[0]), Args: []string{}, } if len(args) > 1 { for _, arg := range args[1:] { ccInput.Args = append(ccInput.Args, string(arg)) } } if proposalPayload.TransientMap != nil { tm := make(map[string]string) for k, v := range proposalPayload.TransientMap { tm[k] = string(v) } if tb, err := json.Marshal(tm); err != nil { logger.Errorf("failed to marshal transient map to JSON: %+v", err) } else { ccInput.TransientMap = string(tb) } } // action response payload prespPayload, err := UnmarshalProposalResponsePayload(ccAction.Action.ProposalResponsePayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal response payload") } cact, err := UnmarshalChaincodeAction(prespPayload.Extension) if err != nil { return nil, errors.Wrapf(err, "failed to get chaincode action") } if cact.Response == nil { return nil, errors.New("chaincode response is empty") } if cact.ChaincodeId != nil { ccID.Version = cact.ChaincodeId.Version } // chaincode response ccResult := ChaincodeResult{ Response: &ChaincodeResponse{ Status: cact.Response.Status, Message: cact.Response.Message, Payload: string(cact.Response.Payload), }, } action := ActionDetail{ Chaincode: &ccID, Input: &ccInput, Result: &ccResult, EndorserCount: len(ccAction.Action.Endorsements), } // chaincode result if cact.Results != nil { txrw := &rwset.TxReadWriteSet{} err := proto.Unmarshal(cact.Results, txrw) if err != nil { logger.Errorf("failed to unmarshal tx rwset: %+v", err) } else { ccResult.ReadWriteCount = len(txrw.NsRwset) } } // chaincode event if cact.Events != nil { if ccEvt, err := UnmarshalChaincodeEvents(cact.Events); err != nil { logger.Errorf("failed to get chaincode event: %+v", err) } else { ccResult.Event = &ChaincodeEvent{ Name: ccEvt.EventName, Payload: string(ccEvt.Payload), } } } return &action, nil } // CCEventDetail contains data in a chaincode event type CCEventDetail struct { BlockNumber uint64 `json:"block"` SourceURL string `json:"source,omitempty"` TxID string `json:"txId"` ChaincodeID string `json:"chaincode"` EventName string `json:"name"` Payload string `json:"payload"` } // BlockEventDetail contains data in a block event type BlockEventDetail struct { Number uint64 `json:"block"` SourceURL string `json:"source,omitempty"` Transactions []*TransactionDetail `json:"transactions"` } // TransactionDetail contains data in a transaction type TransactionDetail struct { TxType string `json:"type"` TxID string `json:"txId"` TxTime string `json:"txTime,omitempty"` ChannelID string `json:"channel"` CreatorIdentity *Identity `json:"creator,omitempty"` Actions []*ActionDetail `json:"actions,omitempty"` } // Identity contains creator's mspid and certificate type Identity struct { Mspid string `json:"mspid"` Subject string `json:"subject,omitempty"` Issuer string `json:"issuer,omitempty"` Cert string `json:"cert,omitempty"` } // ActionDetail contains data in a chaincode invocation type ActionDetail struct { Chaincode *ChaincodeID `json:"chaincode,omitempty"` Input *ChaincodeInput `json:"input,omitempty"` Result *ChaincodeResult `json:"result,omitempty"` EndorserCount int `json:"endorsers,omitempty"` } // ChaincodeID defines chaincode identity type ChaincodeID struct { Type string `json:"type,omitempty"` Name string `json:"name"` Version string `json:"version,omitempty"` } // ChaincodeInput defines input parameters of a chaincode invocation type ChaincodeInput struct { Function string `json:"function"` Args []string `json:"args,omitempty"` TransientMap string `json:"transient,omitempty"` } // ChaincodeResult defines result of a chaincode invocation type ChaincodeResult struct { ReadWriteCount int `json:"rwset,omitempty"` Response *ChaincodeResponse `json:"response,omitempty"` Event *ChaincodeEvent `json:"event,omitempty"` } // ChaincodeResponse defines response from a chaincode invocation type ChaincodeResponse struct { Status int32 `json:"status"` Message string `json:"message,omitempty"` Payload string `json:"payload,omitempty"` } // ChaincodeEvent defines event created by a chaincode invocation type ChaincodeEvent struct { Name string `json:"name"` Payload string `json:"payload,omitempty"` } func networkConfigProvider(networkConfig []byte, entityMatcherOverride []byte) core.ConfigProvider { configProvider := config.FromRaw(networkConfig, "yaml") if entityMatcherOverride != nil { return func() ([]core.ConfigBackend, error) { matcherProvider := config.FromRaw(entityMatcherOverride, "yaml") matcherBackends, err := matcherProvider() if err != nil { logger.Errorf("failed to parse entity matchers: %+v", err) // return the original config provider defined by configPath return configProvider() } currentBackends, err := configProvider() if err != nil { logger.Errorf("failed to parse network config: %+v", err) return nil, err } // return the combined config with matcher precedency return append(matcherBackends, currentBackends...), nil } } return configProvider }
unmarshalFilteredBlockEvent
identifier_name
listener.go
package eventlistener import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "time" "github.com/pkg/errors" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric-protos-go/ledger/rwset" "github.com/hyperledger/fabric-protos-go/msp" pb "github.com/hyperledger/fabric-protos-go/peer" "github.com/hyperledger/fabric-sdk-go/pkg/client/event" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) const ( // EventBlock type for block event EventBlock = "Block" // EventFiltered type for filtered block event EventFiltered = "Filtered Block" // EventChaincode type for chaincode event EventChaincode = "Chaincode" ) // cllientMap var clientMap = map[string]*event.Client{} // EventHandler defines action on event data type EventHandler func(data interface{}) // Listener caches event listener info type Listener struct { client *event.Client eventType string chaincodeID string eventFilter string handler EventHandler stopchan chan struct{} exitchan chan struct{} } // NewListener creates a lisenter instance func NewListener(spec *Spec, handler EventHandler) (*Listener, error) { client, err := getEventClient(spec) if err != nil { return nil, err } listener := Listener{ client: client, eventType: spec.EventType, chaincodeID: spec.ChaincodeID, eventFilter: spec.EventFilter, handler: handler, } return &listener, nil } // Start starts the event listener func (c *Listener) Start() error { switch c.eventType { case EventBlock: // register and wait for one block event registration, blkChan, err := c.client.RegisterBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register block event") } logger.Info("block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveBlockEvent(blkChan, c.handler, c.stopchan) }() case EventFiltered: // register and wait for one filtered block event registration, blkChan, err := c.client.RegisterFilteredBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register filtered block event") } logger.Info("filtered block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan) }() case EventChaincode: // register and wait for one chaincode event registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilter) if err != nil { return errors.Wrapf(err, "Failed to register chaincode event") } logger.Info("chaincode event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveChaincodeEvent(ccChan, c.handler, c.stopchan) }() default: logger.Infof("event type '%s' is not supported", c.eventType) } return nil } // Stop stops the event listener func (c *Listener) Stop() { logger.Info("Stop listener ...") close(c.stopchan) <-c.exitchan logger.Info("Listener stopped") } // Spec defines client for fabric events type Spec struct { Name string NetworkConfig []byte EntityMatchers []byte OrgName string UserName string ChannelID string EventType string ChaincodeID string EventFilter string } func clientID(spec *Spec) string { return fmt.Sprintf("%s.%s.%s.%t", spec.Name, spec.UserName, spec.OrgName, spec.EventType != EventFiltered) } // getEventClient returns cached event client or create a new event client if it does not exist func getEventClient(spec *Spec) (*event.Client, error) { cid := clientID(spec) client, ok := clientMap[cid] if ok && client != nil { return client, nil } // create new event client sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers)) if err != nil { return nil, errors.Wrapf(err, "Failed to create new SDK") } opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)} if spec.OrgName != "" { opts = append(opts, fabsdk.WithOrg(spec.OrgName)) } if spec.EventType == EventFiltered { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...)) } else { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents()) } if err != nil { clientMap[cid] = client } return client, err } func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) { for { var ccEvent *fab.CCEvent select { case ccEvent = <-ccChan: cce := unmarshalChaincodeEvent(ccEvent) handler(cce) case <-stopchan: logger.Info("Quit listener for chaincode event") return } } } func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail { ced := CCEventDetail{ BlockNumber: ccEvent.BlockNumber, SourceURL: ccEvent.SourceURL, TxID: ccEvent.TxID, ChaincodeID: ccEvent.ChaincodeID, EventName: ccEvent.EventName, Payload: string(ccEvent.Payload), } return &ced } func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.FilteredBlockEvent select { case blkEvent = <-blkChan: bed := unmarshalFilteredBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for filtered block event") return } } } func unmarshalFilteredBlockEvent(blkEvent *fab.FilteredBlockEvent) *BlockEventDetail { blk := blkEvent.FilteredBlock // blkjson, _ := json.Marshal(blk) // fmt.Println(string(blkjson)) bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blk.Number, Transactions: []*TransactionDetail{}, } for _, d := range blk.FilteredTransactions { td := TransactionDetail{ TxType: common.HeaderType_name[int32(d.Type)], TxID: d.Txid, ChannelID: blk.ChannelId, Actions: []*ActionDetail{}, } bed.Transactions = append(bed.Transactions, &td) actions := d.GetTransactionActions() if actions != nil { for _, ta := range actions.ChaincodeActions { ce := ta.GetChaincodeEvent() if ce != nil && ce.ChaincodeId != "" { action := ActionDetail{ Chaincode: &ChaincodeID{Name: ce.ChaincodeId}, Result: &ChaincodeResult{ Event: &ChaincodeEvent{ Name: ce.EventName, Payload: string(ce.Payload), }, }, } td.Actions = append(td.Actions, &action) } } } } return &bed } func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.BlockEvent select { case blkEvent = <-blkChan: bed := unmarshalBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for block event") return } } } func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail { bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blkEvent.Block.Header.Number, Transactions: []*TransactionDetail{}, } for _, d := range blkEvent.Block.Data.Data { txn, err := unmarshalTransaction(d) if err != nil { logger.Errorf("Error unmarshalling transaction: %+v", err) continue } else { bed.Transactions = append(bed.Transactions, txn) } } return &bed } func unmarshalTransaction(data []byte) (*TransactionDetail, error) { envelope, err := GetEnvelopeFromBlock(data) if err != nil { return nil, errors.Wrapf(err, "failed to get envelope") } payload, err := UnmarshalPayload(envelope.Payload) if err != nil { return nil, errors.Wrapf(err, "failed to get payload") } if payload.Header == nil { return nil, errors.Errorf("payload header is empty") } // channel header chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal channel header") } td := TransactionDetail{ TxType: common.HeaderType_name[chdr.Type], TxID: chdr.TxId, TxTime: time.Unix(chdr.Timestamp.Seconds, int64(chdr.Timestamp.Nanos)).UTC().String(), ChannelID: chdr.ChannelId, Actions: []*ActionDetail{}, } // signature header shdr := &common.SignatureHeader{} if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil { logger.Errorf("failed to unmarshal signature header: %+v", err) } else { cid, err := unmarshalIdentity(shdr.Creator) if err != nil { logger.Errorf("failed to unmarshal creator identity: %+v", err) } else { td.CreatorIdentity = cid } } txn, err := UnmarshalTransaction(payload.Data) if err != nil { return &td, errors.Wrapf(err, "failed to get transaction") } for _, ta := range txn.Actions { act, err := unmarshalAction(ta.Payload) if err != nil { logger.Errorf("Error unmarshalling action: %+v", err) continue } else { td.Actions = append(td.Actions, act) } } return &td, nil } func unmarshalIdentity(data []byte) (*Identity, error) { cid := &msp.SerializedIdentity{} if err := proto.Unmarshal(data, cid); err != nil { return nil, err } id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)} // extract info from x509 certificate block, _ := pem.Decode(cid.IdBytes) if block == nil { logger.Info("creator certificate is empty") return &id, nil } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { logger.Errorf("failed to parse creator certificate: %+v", err) return &id, nil } id.Subject = cert.Subject.CommonName id.Issuer = cert.Issuer.CommonName return &id, nil } func unmarshalAction(data []byte) (*ActionDetail, error) { ccAction, err := UnmarshalChaincodeActionPayload(data) if err != nil { return nil, errors.Wrapf(err, "failed to get action payload") } // proposal payload proposalPayload, err := UnmarshalChaincodeProposalPayload(ccAction.ChaincodeProposalPayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal payload") } cis := &pb.ChaincodeInvocationSpec{} err = proto.Unmarshal(proposalPayload.Input, cis) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal chaincode input") } // chaincode spec ccID := ChaincodeID{ Type: pb.ChaincodeSpec_Type_name[int32(cis.ChaincodeSpec.Type)], Name: cis.ChaincodeSpec.ChaincodeId.Name, } // chaincode input args := cis.ChaincodeSpec.Input.Args ccInput := ChaincodeInput{ Function: string(args[0]), Args: []string{}, } if len(args) > 1 { for _, arg := range args[1:] { ccInput.Args = append(ccInput.Args, string(arg)) } } if proposalPayload.TransientMap != nil
// action response payload prespPayload, err := UnmarshalProposalResponsePayload(ccAction.Action.ProposalResponsePayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal response payload") } cact, err := UnmarshalChaincodeAction(prespPayload.Extension) if err != nil { return nil, errors.Wrapf(err, "failed to get chaincode action") } if cact.Response == nil { return nil, errors.New("chaincode response is empty") } if cact.ChaincodeId != nil { ccID.Version = cact.ChaincodeId.Version } // chaincode response ccResult := ChaincodeResult{ Response: &ChaincodeResponse{ Status: cact.Response.Status, Message: cact.Response.Message, Payload: string(cact.Response.Payload), }, } action := ActionDetail{ Chaincode: &ccID, Input: &ccInput, Result: &ccResult, EndorserCount: len(ccAction.Action.Endorsements), } // chaincode result if cact.Results != nil { txrw := &rwset.TxReadWriteSet{} err := proto.Unmarshal(cact.Results, txrw) if err != nil { logger.Errorf("failed to unmarshal tx rwset: %+v", err) } else { ccResult.ReadWriteCount = len(txrw.NsRwset) } } // chaincode event if cact.Events != nil { if ccEvt, err := UnmarshalChaincodeEvents(cact.Events); err != nil { logger.Errorf("failed to get chaincode event: %+v", err) } else { ccResult.Event = &ChaincodeEvent{ Name: ccEvt.EventName, Payload: string(ccEvt.Payload), } } } return &action, nil } // CCEventDetail contains data in a chaincode event type CCEventDetail struct { BlockNumber uint64 `json:"block"` SourceURL string `json:"source,omitempty"` TxID string `json:"txId"` ChaincodeID string `json:"chaincode"` EventName string `json:"name"` Payload string `json:"payload"` } // BlockEventDetail contains data in a block event type BlockEventDetail struct { Number uint64 `json:"block"` SourceURL string `json:"source,omitempty"` Transactions []*TransactionDetail `json:"transactions"` } // TransactionDetail contains data in a transaction type TransactionDetail struct { TxType string `json:"type"` TxID string `json:"txId"` TxTime string `json:"txTime,omitempty"` ChannelID string `json:"channel"` CreatorIdentity *Identity `json:"creator,omitempty"` Actions []*ActionDetail `json:"actions,omitempty"` } // Identity contains creator's mspid and certificate type Identity struct { Mspid string `json:"mspid"` Subject string `json:"subject,omitempty"` Issuer string `json:"issuer,omitempty"` Cert string `json:"cert,omitempty"` } // ActionDetail contains data in a chaincode invocation type ActionDetail struct { Chaincode *ChaincodeID `json:"chaincode,omitempty"` Input *ChaincodeInput `json:"input,omitempty"` Result *ChaincodeResult `json:"result,omitempty"` EndorserCount int `json:"endorsers,omitempty"` } // ChaincodeID defines chaincode identity type ChaincodeID struct { Type string `json:"type,omitempty"` Name string `json:"name"` Version string `json:"version,omitempty"` } // ChaincodeInput defines input parameters of a chaincode invocation type ChaincodeInput struct { Function string `json:"function"` Args []string `json:"args,omitempty"` TransientMap string `json:"transient,omitempty"` } // ChaincodeResult defines result of a chaincode invocation type ChaincodeResult struct { ReadWriteCount int `json:"rwset,omitempty"` Response *ChaincodeResponse `json:"response,omitempty"` Event *ChaincodeEvent `json:"event,omitempty"` } // ChaincodeResponse defines response from a chaincode invocation type ChaincodeResponse struct { Status int32 `json:"status"` Message string `json:"message,omitempty"` Payload string `json:"payload,omitempty"` } // ChaincodeEvent defines event created by a chaincode invocation type ChaincodeEvent struct { Name string `json:"name"` Payload string `json:"payload,omitempty"` } func networkConfigProvider(networkConfig []byte, entityMatcherOverride []byte) core.ConfigProvider { configProvider := config.FromRaw(networkConfig, "yaml") if entityMatcherOverride != nil { return func() ([]core.ConfigBackend, error) { matcherProvider := config.FromRaw(entityMatcherOverride, "yaml") matcherBackends, err := matcherProvider() if err != nil { logger.Errorf("failed to parse entity matchers: %+v", err) // return the original config provider defined by configPath return configProvider() } currentBackends, err := configProvider() if err != nil { logger.Errorf("failed to parse network config: %+v", err) return nil, err } // return the combined config with matcher precedency return append(matcherBackends, currentBackends...), nil } } return configProvider }
{ tm := make(map[string]string) for k, v := range proposalPayload.TransientMap { tm[k] = string(v) } if tb, err := json.Marshal(tm); err != nil { logger.Errorf("failed to marshal transient map to JSON: %+v", err) } else { ccInput.TransientMap = string(tb) } }
conditional_block
listener.go
package eventlistener import ( "crypto/x509" "encoding/json" "encoding/pem" "fmt" "time" "github.com/pkg/errors" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric-protos-go/ledger/rwset" "github.com/hyperledger/fabric-protos-go/msp" pb "github.com/hyperledger/fabric-protos-go/peer" "github.com/hyperledger/fabric-sdk-go/pkg/client/event" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/core" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) const ( // EventBlock type for block event EventBlock = "Block" // EventFiltered type for filtered block event EventFiltered = "Filtered Block" // EventChaincode type for chaincode event EventChaincode = "Chaincode" ) // cllientMap var clientMap = map[string]*event.Client{} // EventHandler defines action on event data type EventHandler func(data interface{}) // Listener caches event listener info type Listener struct { client *event.Client eventType string chaincodeID string eventFilter string handler EventHandler stopchan chan struct{} exitchan chan struct{} } // NewListener creates a lisenter instance func NewListener(spec *Spec, handler EventHandler) (*Listener, error) { client, err := getEventClient(spec) if err != nil { return nil, err } listener := Listener{ client: client, eventType: spec.EventType, chaincodeID: spec.ChaincodeID, eventFilter: spec.EventFilter, handler: handler, } return &listener, nil } // Start starts the event listener func (c *Listener) Start() error { switch c.eventType { case EventBlock: // register and wait for one block event registration, blkChan, err := c.client.RegisterBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register block event") } logger.Info("block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveBlockEvent(blkChan, c.handler, c.stopchan) }() case EventFiltered: // register and wait for one filtered block event registration, blkChan, err := c.client.RegisterFilteredBlockEvent() if err != nil { return errors.Wrapf(err, "Failed to register filtered block event") } logger.Info("filtered block event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan) }() case EventChaincode: // register and wait for one chaincode event registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilter) if err != nil { return errors.Wrapf(err, "Failed to register chaincode event") } logger.Info("chaincode event registered successfully") c.stopchan = make(chan struct{}) c.exitchan = make(chan struct{}) go func() { defer close(c.exitchan) defer c.client.Unregister(registration) receiveChaincodeEvent(ccChan, c.handler, c.stopchan) }() default: logger.Infof("event type '%s' is not supported", c.eventType) } return nil } // Stop stops the event listener func (c *Listener) Stop() { logger.Info("Stop listener ...") close(c.stopchan) <-c.exitchan logger.Info("Listener stopped") } // Spec defines client for fabric events type Spec struct { Name string NetworkConfig []byte EntityMatchers []byte OrgName string UserName string ChannelID string EventType string ChaincodeID string EventFilter string } func clientID(spec *Spec) string { return fmt.Sprintf("%s.%s.%s.%t", spec.Name, spec.UserName, spec.OrgName, spec.EventType != EventFiltered) } // getEventClient returns cached event client or create a new event client if it does not exist func getEventClient(spec *Spec) (*event.Client, error) { cid := clientID(spec) client, ok := clientMap[cid] if ok && client != nil { return client, nil } // create new event client sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers)) if err != nil { return nil, errors.Wrapf(err, "Failed to create new SDK") } opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)} if spec.OrgName != "" { opts = append(opts, fabsdk.WithOrg(spec.OrgName)) } if spec.EventType == EventFiltered { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...)) } else { client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents()) } if err != nil { clientMap[cid] = client } return client, err } func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) { for { var ccEvent *fab.CCEvent select { case ccEvent = <-ccChan: cce := unmarshalChaincodeEvent(ccEvent) handler(cce) case <-stopchan: logger.Info("Quit listener for chaincode event") return } } } func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail { ced := CCEventDetail{ BlockNumber: ccEvent.BlockNumber, SourceURL: ccEvent.SourceURL, TxID: ccEvent.TxID, ChaincodeID: ccEvent.ChaincodeID, EventName: ccEvent.EventName, Payload: string(ccEvent.Payload), } return &ced } func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.FilteredBlockEvent select { case blkEvent = <-blkChan: bed := unmarshalFilteredBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for filtered block event") return } } } func unmarshalFilteredBlockEvent(blkEvent *fab.FilteredBlockEvent) *BlockEventDetail
func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) { for { var blkEvent *fab.BlockEvent select { case blkEvent = <-blkChan: bed := unmarshalBlockEvent(blkEvent) handler(bed) case <-stopchan: logger.Info("Quit listener for block event") return } } } func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail { bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blkEvent.Block.Header.Number, Transactions: []*TransactionDetail{}, } for _, d := range blkEvent.Block.Data.Data { txn, err := unmarshalTransaction(d) if err != nil { logger.Errorf("Error unmarshalling transaction: %+v", err) continue } else { bed.Transactions = append(bed.Transactions, txn) } } return &bed } func unmarshalTransaction(data []byte) (*TransactionDetail, error) { envelope, err := GetEnvelopeFromBlock(data) if err != nil { return nil, errors.Wrapf(err, "failed to get envelope") } payload, err := UnmarshalPayload(envelope.Payload) if err != nil { return nil, errors.Wrapf(err, "failed to get payload") } if payload.Header == nil { return nil, errors.Errorf("payload header is empty") } // channel header chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal channel header") } td := TransactionDetail{ TxType: common.HeaderType_name[chdr.Type], TxID: chdr.TxId, TxTime: time.Unix(chdr.Timestamp.Seconds, int64(chdr.Timestamp.Nanos)).UTC().String(), ChannelID: chdr.ChannelId, Actions: []*ActionDetail{}, } // signature header shdr := &common.SignatureHeader{} if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil { logger.Errorf("failed to unmarshal signature header: %+v", err) } else { cid, err := unmarshalIdentity(shdr.Creator) if err != nil { logger.Errorf("failed to unmarshal creator identity: %+v", err) } else { td.CreatorIdentity = cid } } txn, err := UnmarshalTransaction(payload.Data) if err != nil { return &td, errors.Wrapf(err, "failed to get transaction") } for _, ta := range txn.Actions { act, err := unmarshalAction(ta.Payload) if err != nil { logger.Errorf("Error unmarshalling action: %+v", err) continue } else { td.Actions = append(td.Actions, act) } } return &td, nil } func unmarshalIdentity(data []byte) (*Identity, error) { cid := &msp.SerializedIdentity{} if err := proto.Unmarshal(data, cid); err != nil { return nil, err } id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)} // extract info from x509 certificate block, _ := pem.Decode(cid.IdBytes) if block == nil { logger.Info("creator certificate is empty") return &id, nil } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { logger.Errorf("failed to parse creator certificate: %+v", err) return &id, nil } id.Subject = cert.Subject.CommonName id.Issuer = cert.Issuer.CommonName return &id, nil } func unmarshalAction(data []byte) (*ActionDetail, error) { ccAction, err := UnmarshalChaincodeActionPayload(data) if err != nil { return nil, errors.Wrapf(err, "failed to get action payload") } // proposal payload proposalPayload, err := UnmarshalChaincodeProposalPayload(ccAction.ChaincodeProposalPayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal payload") } cis := &pb.ChaincodeInvocationSpec{} err = proto.Unmarshal(proposalPayload.Input, cis) if err != nil { return nil, errors.Wrapf(err, "failed to unmarshal chaincode input") } // chaincode spec ccID := ChaincodeID{ Type: pb.ChaincodeSpec_Type_name[int32(cis.ChaincodeSpec.Type)], Name: cis.ChaincodeSpec.ChaincodeId.Name, } // chaincode input args := cis.ChaincodeSpec.Input.Args ccInput := ChaincodeInput{ Function: string(args[0]), Args: []string{}, } if len(args) > 1 { for _, arg := range args[1:] { ccInput.Args = append(ccInput.Args, string(arg)) } } if proposalPayload.TransientMap != nil { tm := make(map[string]string) for k, v := range proposalPayload.TransientMap { tm[k] = string(v) } if tb, err := json.Marshal(tm); err != nil { logger.Errorf("failed to marshal transient map to JSON: %+v", err) } else { ccInput.TransientMap = string(tb) } } // action response payload prespPayload, err := UnmarshalProposalResponsePayload(ccAction.Action.ProposalResponsePayload) if err != nil { return nil, errors.Wrapf(err, "failed to get proposal response payload") } cact, err := UnmarshalChaincodeAction(prespPayload.Extension) if err != nil { return nil, errors.Wrapf(err, "failed to get chaincode action") } if cact.Response == nil { return nil, errors.New("chaincode response is empty") } if cact.ChaincodeId != nil { ccID.Version = cact.ChaincodeId.Version } // chaincode response ccResult := ChaincodeResult{ Response: &ChaincodeResponse{ Status: cact.Response.Status, Message: cact.Response.Message, Payload: string(cact.Response.Payload), }, } action := ActionDetail{ Chaincode: &ccID, Input: &ccInput, Result: &ccResult, EndorserCount: len(ccAction.Action.Endorsements), } // chaincode result if cact.Results != nil { txrw := &rwset.TxReadWriteSet{} err := proto.Unmarshal(cact.Results, txrw) if err != nil { logger.Errorf("failed to unmarshal tx rwset: %+v", err) } else { ccResult.ReadWriteCount = len(txrw.NsRwset) } } // chaincode event if cact.Events != nil { if ccEvt, err := UnmarshalChaincodeEvents(cact.Events); err != nil { logger.Errorf("failed to get chaincode event: %+v", err) } else { ccResult.Event = &ChaincodeEvent{ Name: ccEvt.EventName, Payload: string(ccEvt.Payload), } } } return &action, nil } // CCEventDetail contains data in a chaincode event type CCEventDetail struct { BlockNumber uint64 `json:"block"` SourceURL string `json:"source,omitempty"` TxID string `json:"txId"` ChaincodeID string `json:"chaincode"` EventName string `json:"name"` Payload string `json:"payload"` } // BlockEventDetail contains data in a block event type BlockEventDetail struct { Number uint64 `json:"block"` SourceURL string `json:"source,omitempty"` Transactions []*TransactionDetail `json:"transactions"` } // TransactionDetail contains data in a transaction type TransactionDetail struct { TxType string `json:"type"` TxID string `json:"txId"` TxTime string `json:"txTime,omitempty"` ChannelID string `json:"channel"` CreatorIdentity *Identity `json:"creator,omitempty"` Actions []*ActionDetail `json:"actions,omitempty"` } // Identity contains creator's mspid and certificate type Identity struct { Mspid string `json:"mspid"` Subject string `json:"subject,omitempty"` Issuer string `json:"issuer,omitempty"` Cert string `json:"cert,omitempty"` } // ActionDetail contains data in a chaincode invocation type ActionDetail struct { Chaincode *ChaincodeID `json:"chaincode,omitempty"` Input *ChaincodeInput `json:"input,omitempty"` Result *ChaincodeResult `json:"result,omitempty"` EndorserCount int `json:"endorsers,omitempty"` } // ChaincodeID defines chaincode identity type ChaincodeID struct { Type string `json:"type,omitempty"` Name string `json:"name"` Version string `json:"version,omitempty"` } // ChaincodeInput defines input parameters of a chaincode invocation type ChaincodeInput struct { Function string `json:"function"` Args []string `json:"args,omitempty"` TransientMap string `json:"transient,omitempty"` } // ChaincodeResult defines result of a chaincode invocation type ChaincodeResult struct { ReadWriteCount int `json:"rwset,omitempty"` Response *ChaincodeResponse `json:"response,omitempty"` Event *ChaincodeEvent `json:"event,omitempty"` } // ChaincodeResponse defines response from a chaincode invocation type ChaincodeResponse struct { Status int32 `json:"status"` Message string `json:"message,omitempty"` Payload string `json:"payload,omitempty"` } // ChaincodeEvent defines event created by a chaincode invocation type ChaincodeEvent struct { Name string `json:"name"` Payload string `json:"payload,omitempty"` } func networkConfigProvider(networkConfig []byte, entityMatcherOverride []byte) core.ConfigProvider { configProvider := config.FromRaw(networkConfig, "yaml") if entityMatcherOverride != nil { return func() ([]core.ConfigBackend, error) { matcherProvider := config.FromRaw(entityMatcherOverride, "yaml") matcherBackends, err := matcherProvider() if err != nil { logger.Errorf("failed to parse entity matchers: %+v", err) // return the original config provider defined by configPath return configProvider() } currentBackends, err := configProvider() if err != nil { logger.Errorf("failed to parse network config: %+v", err) return nil, err } // return the combined config with matcher precedency return append(matcherBackends, currentBackends...), nil } } return configProvider }
{ blk := blkEvent.FilteredBlock // blkjson, _ := json.Marshal(blk) // fmt.Println(string(blkjson)) bed := BlockEventDetail{ SourceURL: blkEvent.SourceURL, Number: blk.Number, Transactions: []*TransactionDetail{}, } for _, d := range blk.FilteredTransactions { td := TransactionDetail{ TxType: common.HeaderType_name[int32(d.Type)], TxID: d.Txid, ChannelID: blk.ChannelId, Actions: []*ActionDetail{}, } bed.Transactions = append(bed.Transactions, &td) actions := d.GetTransactionActions() if actions != nil { for _, ta := range actions.ChaincodeActions { ce := ta.GetChaincodeEvent() if ce != nil && ce.ChaincodeId != "" { action := ActionDetail{ Chaincode: &ChaincodeID{Name: ce.ChaincodeId}, Result: &ChaincodeResult{ Event: &ChaincodeEvent{ Name: ce.EventName, Payload: string(ce.Payload), }, }, } td.Actions = append(td.Actions, &action) } } } } return &bed }
identifier_body
som.py
import get_datasets as gd import os import time from glob import glob import tensorflow as tf import numpy as np from collections import namedtuple import re #PANDAS from pandas.core.frame import DataFrame import pandas as pd import igraph as ig from enum import Enum #SKLEARN from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA #PLOTLY import plotly.tools import plotly.plotly as py import plotly.io as pio import plotly.graph_objs as go from asn1crypto.core import InstanceOf import sklearn import os plotly.tools.set_credentials_file(username='isonettv', api_key='2Lg1USMkZAHONqo82eMG') ''' The mode used in a cycle. Can be one of: TRAIN: to use when training the model TEST: to use when testing the model ''' Mode = Enum("Mode","TRAIN TEST PRED") ''' Neighborhood function h_ij to be used. Can be one of: GAUSSIAN: Uses a gaussian with decay equal to self.sigma on the neighborhood CONSTANT: 1 if in neighborhood, 0 otherwise ''' NFunc = Enum("NFunc","GAUSSIAN CONSTANT") ''' Initialization of the initial points.Can be one of: RANDOM: Initializes each points randomly inside (-self.init_maxval,+self.init_maxval) PCAINIT: Uses the 2 principal components to unfold a grid ''' InitMode = Enum("InitMode","RANDOM PCAINIT") ''' Configuration for the plot operation.Can be one of: CLASS_COLOR: Shows the class attr. of unlabeled points through color CLASS_NOCOLOR: All unlabeled points have the same color ''' PlotMode = Enum("PlotMode","CLASS_COLOR CLASS_NOCOLOR") ''' Configuration for grid type. Can be one of: RECTANGLE: Use rectangular grid HEXAGON: Use hexagonal grid ''' GridMode = Enum("GridMode","RECTANGLE HEXAGON") class som(object): ''' Creates a Self-Organizing Map (SOM). It has a couple of parameters to be selected by using the "args" object. These include: self.N1: Number of nodes in each row of the grid self.N2: Number of nodes in each column of the grid self.eps_i, self.eps_f: initial and final values of epsilon. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.sigma_i, self.sigma_f: initial and final values of sigma. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.ntype: Neighborhood type self.plotmode: which plot to make self.initmode: how to initialize grid self.gridmode: which type of grid self.ds_name: Name of dataset (iris,isolet,wine,grid) ''' ''' Initializes the Growing Neural Gas Network @param sess: the current session @param args: object containing arguments (see main.py) ''' def __init__(self, sess, args): # Parameters self.sess = sess self.run_id = args.run_id #Number of nodes in each row of the grid self.N1 = args.n1 #Number of nodes in each column of the grid self.N2 = args.n2 #Initial and final values of epsilon self.eps_i = args.eps_i self.eps_f = args.eps_f #Initial and final values of sigma self.sigma_i = args.sigma_i self.sigma_f = args.sigma_f #Neighborhood type self.ntype = NFunc[args.ntype] #Which plot to make self.plotmode = PlotMode[args.plotmode] #Grid Mode self.gridmode = GridMode[args.gridmode] self.nsize = 1 #Which way to initialize points self.initmode = InitMode[args.initmode] #dataset chosen self.ds_name = args.dataset #Total number of iterations self.n_iter = args.n_iter #Number of iterations between plot op self.plot_iter = args.plot_iter self.characteristics_dict = \ {"dataset":str(self.ds_name), "num_iter":self.n_iter, "n1":self.N1, "n2":self.N2, "eps_i":self.eps_i, "eps_f":self.eps_f, "sigma_i":self.sigma_i, "ntype":self.ntype.name, "initmode":self.initmode.name, "gridmode":self.gridmode.name, "run_id":self.run_id } #Get datasets if args.dataset == "isolet": temp = gd.get_isolet(test_subset= args.cv) elif args.dataset == "iris": temp = gd.get_iris(args.cv) elif args.dataset == "wine": temp = gd.get_wine(args.cv) elif args.dataset == "grid" or args.dataset == "box": temp = gd.get_grid() else: raise ValueError("Bad dataset name") #Create Dataset if isinstance(temp,dict) and 'train' in temp.keys(): self.ds = temp["train"].concatenate(temp["test"]) else: self.ds = temp #Store number of dataset elements and input dimension self.ds_size = self.getNumElementsOfDataset(self.ds) self.ds_inputdim = self.getInputShapeOfDataset(self.ds) #Normalize dataset temp = self.normalizedDataset(self.ds) self.ds = temp["dataset"] df_x_normalized = temp["df_x"] self.Y = temp["df_y"] #Get PCA for dataset print("Generating PCA for further plotting...") self.pca = PCA(n_components=3) self.input_pca = self.pca.fit_transform(df_x_normalized) self.input_pca_scatter = self.inputScatter3D() self.input_pca_maxval = -np.sort(-np.abs(np.reshape(self.input_pca,[-1])),axis=0)[5] print("Done!") print("Dimensionality of Y:{}",self.ds_inputdim) self.ds = self.ds.shuffle(buffer_size=10000).repeat() if args.dataset == "box": self.ds = gd.get_box() #Now generate iterators for dataset self.iterator_ds = self.ds.make_initializable_iterator() self.iter_next = self.iterator_ds.get_next() # tf Graph input self.X_placeholder = tf.placeholder("float", [self.ds_inputdim]) self.W_placeholder = tf.placeholder("float", [self.N1*self.N2,self.ds_inputdim]) self.nborhood_size_placeholder = tf.placeholder("int32", []) self.sigma_placeholder = tf.placeholder("float", []) self.eps_placeholder = tf.placeholder("float", []) print("Initializing graph and global vars...") self.init_graph() # Initializing the variables self.init = tf.global_variables_initializer() print("Done!") ''' Transforms dataset back to dataframe''' def getDatasetAsDF(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break return({"df_x":df_x,"df_y":df_y}) ''' Returns the total number of elements of a dataset @param dataset: the given dataset @return: total number of elements ''' def getNumElementsOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: self.sess.run(next_element) num_elems += 1 except tf.errors.OutOfRangeError: break return num_elems ''' Returns the dimensionality of the first element of dataset @param dataset: the given dataset @return: total number of elements ''' def getInputShapeOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() d = None try: self.sess.run(next_element) d = next_element["X"].shape[0] except tf.errors.OutOfRangeError: return d return int(d) ''' Returns the normalized version of a given dataset @param dataset: the given dataset, such that each element returns an "X" and "Y" @return: dict, with keys "df_x": normalized elements, "df_y": corresponding class attr., "dataset": normalized dataset ("X" and "Y") ''' def normalizedDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break df_x = StandardScaler().fit_transform(df_x) print(df_y) return({"df_x": df_x, "df_y": df_y, "dataset": tf.data.Dataset.from_tensor_slices({"X":df_x,"Y":df_y}) \ }) ''' Initializes the SOM graph ''' def init_graph(self): #initial topology self.g = ig.Graph() self.g.add_vertices(self.N1*self.N2) incr = [(0,1),(0,-1),(1,0),(-1,0)] def isvalid(x): return(x[0] >= 0 and x[0] < self.N1 and\ x[1] >= 0 and x[1] < self.N2) def toOneDim(x): return x[0]*self.N2 + x[1] def sum_tuple(x,y): return(tuple(sum(pair) for pair in zip(x,y))) edges = [] #Add edges for i in np.arange(self.N1): for j in np.arange(self.N2): curr = (i,j) self.g.vs[toOneDim(curr)]["i"] = i self.g.vs[toOneDim(curr)]["j"] = j if self.gridmode.name == "RECTANGLE": incr = [(0,1),(0,-1),(1,0),(-1,0)] else: if i % 2 == 0: incr = [(0,1),(0,-1),(-1,-1),(-1,0),(1,-1),(1,0)] else: incr = [(0,1),(0,-1),(-1,1),(-1,0),(1,1),(1,0)] nbors = list(map(lambda x: sum_tuple(x,curr),incr)) nbors_exist = list(map(lambda x: isvalid(x),nbors)) for n in np.arange(len(nbors)): if nbors_exist[n]: edges += [(toOneDim(curr), toOneDim(nbors[n]))] print(str(curr) + "->" + str(nbors[n]) ) self.g.add_edges(edges) self.g.es["age"] = 0 #self.ID: maps index of each node to its corresponding position tuple (line, col) self.ID = np.array(list(map(lambda x: [self.g.vs[x]["i"],self.g.vs[x]["j"]],\ np.arange(self.N1*self.N2))),dtype=np.int32 ) self.ID = np.reshape(self.ID,(-1,2)) #Initialize distances print("Calculating distances...") self.D = np.array(self.g.shortest_paths(source=None, target=None, weights=None, mode=ig.ALL),dtype=np.int32) print("Done!") def build_model(self): X = self.X_placeholder W = self.W_placeholder nsize = self.nborhood_size_placeholder sigma = self.sigma_placeholder eps = self.eps_placeholder #Step 3: Calculate dist_vecs (vector and magnitude) self.dist_vecs = tf.map_fn(lambda w: X - w,W) self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W) #Step 4:Calculate 2 best self.s = tf.math.top_k(-self.squared_distances,k=2) #1D Index of s1_2d,s2_2d self.s1_1d = self.s.indices[0] self.s2_1d = self.s.indices[1] #2d Index of s1_2d,s2_2d self.s1_2d = tf.gather(self.ID,self.s1_1d) self.s2_2d = tf.gather(self.ID,self.s2_1d) #Step 5: Calculate l1 distances #self.l1 = tf.map_fn(lambda x: tf.norm(x-self.s1_2d,ord=1),self.ID) self.l1 = tf.gather(self.D,self.s1_1d) self.mask = tf.reshape(tf.where(self.l1 <= nsize),\ tf.convert_to_tensor([-1])) #Step 6: Calculate neighborhood function values if self.ntype.name == "GAUSSIAN": self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\ /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\ y=tf.zeros(self.l1.shape)), tf.convert_to_tensor([-1])) else: raise ValueError("unknown self.ntype") #Step 6: Update W self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs) def cycle(self, current_iter, mode = Mode["TRAIN"]): nxt = self.sess.run(self.iter_next)["X"] if mode.name == "TRAIN": #Iteration numbers as floats current_iter_f = float(current_iter) n_iter_f = float(self.n_iter) #Get current epsilon and theta eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f) sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f) print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps)) #Get vector distance, square distance self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) self.s1_1d = np.argmin(self.squared_distances,axis=-1) self.s1_2d = self.ID[self.s1_1d] #Get L1 distances #self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID))) self.l1 = self.D[self.s1_1d,:] self.mask = np.reshape(np.where(self.l1 <= sigma),[-1]) if self.ntype.name == "GAUSSIAN": squared_l1 = np.square(self.l1.astype(np.float32)) self.h = np.exp(-squared_l1 /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1]) for i in np.arange(self.N1*self.N2): self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:] elif mode.name == "TEST": self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) #Get first and second activation top_2 = np.argsort(self.squared_distances)[0:2] self.s1_1d = top_2[0] self.s2_1d = top_2[1] self.s1_2d = self.ID[self.s1_1d] self.s2_2d = self.ID[self.s2_1d] #Get topographic error if (self.s2_1d in self.g.neighbors(self.s1_1d)): topographic_error = 0 else: topographic_error = 1 #print("ERROR {}-{};{}-{}".format(self.s1_2d,self.squared_distances[self.s1_1d],\ # self.s2_2d,self.squared_distances[self.s2_1d] )) #Get quantization error quantization_error = (self.squared_distances[self.s1_1d]) return ({"topographic_error":topographic_error,\ "quantization_error":quantization_error}) def train(self): #Run initializer self.sess.run(self.init) self.sess.run(self.iterator_ds.initializer) if self.initmode.name == "PCAINIT": if self.ds_inputdim < 2: raise ValueError("uniform init needs dim input >= 2") self.W = np.zeros([self.N1*self.N2,3]) print(self.W.shape) self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2]) if self.gridmode.name == "HEXAGON": print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))) self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\ ,1] -= 0.5 print(self.W.shape) self.W = np.matmul(self.W,self.pca.components_) print(self.W.shape) self.W = StandardScaler().fit_transform(self.W) print(self.W.shape) else: self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\ dtype=tf.float32)) self.W = StandardScaler().fit_transform(self.W) #BEGIN Training for current_iter in np.arange(self.n_iter): self.cycle(current_iter) if current_iter % self.plot_iter == 0: self.prettygraph(current_iter,mask=self.mask) self.prettygraph(self.n_iter,mask=self.mask,online=True) #END Training #BEGIN Testing self.sess.run(self.iterator_ds.initializer) topographic_error = 0 quantization_error = 0 chosen_Mat = np.zeros((self.N1,self.N2)) for current_iter in np.arange(self.ds_size): cycl = self.cycle(current_iter,mode=Mode["TEST"]) topographic_error += cycl["topographic_error"] quantization_error += cycl["quantization_error"] chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1 topographic_error = topographic_error / self.ds_size quantization_error = quantization_error / self.ds_size #Generate U-Matrix U_Mat = np.zeros((self.N1,self.N2)) for i in np.arange(self.N1): for j in np.arange(self.N2): vert_pos = self.W[i * self.N2 + j] nbors = self.g.neighbors(i * self.N2 + j) d = np.sum(\ list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\ ,nbors))) U_Mat[i,j] = d print("Quantization Error:{}".format(quantization_error)) print("Topographic Error:{}".format(topographic_error)) print(np.array(self.characteristics_dict.keys()) ) df_keys = list(self.characteristics_dict.keys()) +\ ["quantization_error","topographic_error"] df_vals = list(self.characteristics_dict.values()) +\ [quantization_error,topographic_error] #df_vals = [str(x) for x in df_vals] print(df_keys) print(df_vals) print(len(df_keys)) print(len(df_vals)) if os.path.exists("runs.csv"): print("CSV exists") df = pd.read_csv("runs.csv",header=0) df_new = pd.DataFrame(columns=df_keys,index=np.arange(1)) df_new.iloc[0,:] = df_vals df = df.append(df_new,ignore_index=True) else: print("CSV created") df = pd.DataFrame(columns=df_keys,index=np.arange(1)) df.iloc[0,:] = df_vals df.to_csv("runs.csv",index=False) def
(self): Xn = self.input_pca[:,0] Yn = self.input_pca[:,1] Zn = self.input_pca[:,2] Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) ) Y = [int(x) for x in Y] num_class = len(Y) pal = ig.ClusterColoringPalette(num_class) if self.plotmode.name == "CLASS_COLOR": col = pal.get_many(Y) siz = 2 else: col = "green" siz = 1.5 trace0=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='input', marker=dict(symbol='circle', size=siz, color=col, line=dict(color='rgb(50,50,50)', width=0.25) ), text="", hoverinfo='text' ) return(trace0) def prettygraph(self,iter_number, mask,online = False): trace0 = self.input_pca_scatter W = self.pca.transform(self.W) Xn=W[:,0]# x-coordinates of nodes Yn=W[:,1] # y-coordinates if self.ds_name in ["box","grid"]: Zn=self.W[:,2] # z-coordinates else: Zn=W[:,2] # z-coordinates edge_colors = [] Xe=[] Ye=[] Ze=[] num_pallete = 1000 for e in self.g.get_edgelist(): #col = self.g.es.find(_between=((e[0],), (e[1],)),)["age"] #col = float(col)/float(1) #col = min(num_pallete-1, int(num_pallete * col)) #edge_colors += [col,col] Xe+=[W[e[0],0],W[e[1],0],None]# x-coordinates of edge ends Ye+=[W[e[0],1],W[e[1],1],None]# y-coordinates of edge ends Ze+=[W[e[0],2],W[e[1],2],None]# z-coordinates of edge ends #Create Scaling for edges based on Age pal_V = ig.GradientPalette("blue", "black", num_pallete) pal_E = ig.GradientPalette("black", "white", num_pallete) v_colors = ["orange" for a in np.arange(self.g.vcount())] for v in mask: v_colors[v] = "yellow" trace1=go.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=dict(color="black", width=3), hoverinfo='none' ) reference_vec_text = ["m" + str(x) for x in np.arange(self.W.shape[0])] trace2=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='reference_vectors', marker=dict(symbol='square', size=6, color=v_colors, line=dict(color='rgb(50,50,50)', width=0.5) ), text=reference_vec_text, hoverinfo='text' ) axis=dict(showbackground=False, showline=True, zeroline=False, showgrid=False, showticklabels=True, title='', range = [-self.input_pca_maxval-1,1+self.input_pca_maxval] ) layout = go.Layout( title="Visualization of SOM", width=1000, height=1000, showlegend=False, scene=dict( xaxis=dict(axis), yaxis=dict(axis), zaxis=dict(axis), ), margin=dict( t=100 ), hovermode='closest', annotations=[ dict( showarrow=False, text="Data source:</a>", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=dict( size=14 ) ) ], ) data=[trace1, trace2, trace0] fig=go.Figure(data=data, layout=layout) OUTPATH = "./plot/" for k, v in sorted(zip(self.characteristics_dict.keys(),self.characteristics_dict.values()),key = lambda t: (t[0].lower()) ): OUTPATH += str(k)+ "=" + str(v) + ";" OUTPATH = OUTPATH[0:(len(OUTPATH) - 1)] if not os.path.exists(OUTPATH): os.mkdir(OUTPATH) print("Plotting graph...") if online: try: py.iplot(fig) except plotly.exceptions.PlotlyRequestError: print("Warning: Could not plot online") pio.write_image(fig,OUTPATH + "/" + str(iter_number) + ".png") print("Done!")
inputScatter3D
identifier_name
som.py
import get_datasets as gd import os import time from glob import glob import tensorflow as tf import numpy as np from collections import namedtuple import re #PANDAS from pandas.core.frame import DataFrame import pandas as pd import igraph as ig from enum import Enum #SKLEARN from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA #PLOTLY import plotly.tools import plotly.plotly as py import plotly.io as pio import plotly.graph_objs as go from asn1crypto.core import InstanceOf import sklearn import os plotly.tools.set_credentials_file(username='isonettv', api_key='2Lg1USMkZAHONqo82eMG') ''' The mode used in a cycle. Can be one of: TRAIN: to use when training the model TEST: to use when testing the model ''' Mode = Enum("Mode","TRAIN TEST PRED") ''' Neighborhood function h_ij to be used. Can be one of: GAUSSIAN: Uses a gaussian with decay equal to self.sigma on the neighborhood CONSTANT: 1 if in neighborhood, 0 otherwise ''' NFunc = Enum("NFunc","GAUSSIAN CONSTANT") ''' Initialization of the initial points.Can be one of: RANDOM: Initializes each points randomly inside (-self.init_maxval,+self.init_maxval) PCAINIT: Uses the 2 principal components to unfold a grid ''' InitMode = Enum("InitMode","RANDOM PCAINIT") ''' Configuration for the plot operation.Can be one of: CLASS_COLOR: Shows the class attr. of unlabeled points through color CLASS_NOCOLOR: All unlabeled points have the same color ''' PlotMode = Enum("PlotMode","CLASS_COLOR CLASS_NOCOLOR") ''' Configuration for grid type. Can be one of: RECTANGLE: Use rectangular grid HEXAGON: Use hexagonal grid ''' GridMode = Enum("GridMode","RECTANGLE HEXAGON") class som(object): ''' Creates a Self-Organizing Map (SOM). It has a couple of parameters to be selected by using the "args" object. These include: self.N1: Number of nodes in each row of the grid self.N2: Number of nodes in each column of the grid self.eps_i, self.eps_f: initial and final values of epsilon. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.sigma_i, self.sigma_f: initial and final values of sigma. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.ntype: Neighborhood type self.plotmode: which plot to make self.initmode: how to initialize grid self.gridmode: which type of grid self.ds_name: Name of dataset (iris,isolet,wine,grid) ''' ''' Initializes the Growing Neural Gas Network @param sess: the current session @param args: object containing arguments (see main.py) ''' def __init__(self, sess, args): # Parameters self.sess = sess self.run_id = args.run_id #Number of nodes in each row of the grid self.N1 = args.n1 #Number of nodes in each column of the grid self.N2 = args.n2 #Initial and final values of epsilon self.eps_i = args.eps_i self.eps_f = args.eps_f #Initial and final values of sigma self.sigma_i = args.sigma_i self.sigma_f = args.sigma_f #Neighborhood type self.ntype = NFunc[args.ntype] #Which plot to make self.plotmode = PlotMode[args.plotmode] #Grid Mode self.gridmode = GridMode[args.gridmode] self.nsize = 1 #Which way to initialize points self.initmode = InitMode[args.initmode] #dataset chosen self.ds_name = args.dataset #Total number of iterations self.n_iter = args.n_iter #Number of iterations between plot op self.plot_iter = args.plot_iter self.characteristics_dict = \ {"dataset":str(self.ds_name), "num_iter":self.n_iter, "n1":self.N1, "n2":self.N2, "eps_i":self.eps_i, "eps_f":self.eps_f, "sigma_i":self.sigma_i, "ntype":self.ntype.name, "initmode":self.initmode.name, "gridmode":self.gridmode.name, "run_id":self.run_id } #Get datasets if args.dataset == "isolet": temp = gd.get_isolet(test_subset= args.cv) elif args.dataset == "iris": temp = gd.get_iris(args.cv) elif args.dataset == "wine": temp = gd.get_wine(args.cv) elif args.dataset == "grid" or args.dataset == "box": temp = gd.get_grid() else: raise ValueError("Bad dataset name") #Create Dataset if isinstance(temp,dict) and 'train' in temp.keys(): self.ds = temp["train"].concatenate(temp["test"]) else: self.ds = temp #Store number of dataset elements and input dimension self.ds_size = self.getNumElementsOfDataset(self.ds) self.ds_inputdim = self.getInputShapeOfDataset(self.ds) #Normalize dataset temp = self.normalizedDataset(self.ds) self.ds = temp["dataset"] df_x_normalized = temp["df_x"] self.Y = temp["df_y"] #Get PCA for dataset print("Generating PCA for further plotting...") self.pca = PCA(n_components=3) self.input_pca = self.pca.fit_transform(df_x_normalized) self.input_pca_scatter = self.inputScatter3D() self.input_pca_maxval = -np.sort(-np.abs(np.reshape(self.input_pca,[-1])),axis=0)[5] print("Done!") print("Dimensionality of Y:{}",self.ds_inputdim) self.ds = self.ds.shuffle(buffer_size=10000).repeat() if args.dataset == "box": self.ds = gd.get_box() #Now generate iterators for dataset self.iterator_ds = self.ds.make_initializable_iterator() self.iter_next = self.iterator_ds.get_next() # tf Graph input self.X_placeholder = tf.placeholder("float", [self.ds_inputdim]) self.W_placeholder = tf.placeholder("float", [self.N1*self.N2,self.ds_inputdim]) self.nborhood_size_placeholder = tf.placeholder("int32", []) self.sigma_placeholder = tf.placeholder("float", []) self.eps_placeholder = tf.placeholder("float", []) print("Initializing graph and global vars...") self.init_graph() # Initializing the variables self.init = tf.global_variables_initializer() print("Done!") ''' Transforms dataset back to dataframe''' def getDatasetAsDF(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break return({"df_x":df_x,"df_y":df_y}) ''' Returns the total number of elements of a dataset @param dataset: the given dataset @return: total number of elements ''' def getNumElementsOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: self.sess.run(next_element) num_elems += 1 except tf.errors.OutOfRangeError: break return num_elems ''' Returns the dimensionality of the first element of dataset @param dataset: the given dataset @return: total number of elements ''' def getInputShapeOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() d = None try: self.sess.run(next_element) d = next_element["X"].shape[0] except tf.errors.OutOfRangeError: return d return int(d) ''' Returns the normalized version of a given dataset @param dataset: the given dataset, such that each element returns an "X" and "Y" @return: dict, with keys "df_x": normalized elements, "df_y": corresponding class attr., "dataset": normalized dataset ("X" and "Y") ''' def normalizedDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break df_x = StandardScaler().fit_transform(df_x) print(df_y) return({"df_x": df_x, "df_y": df_y, "dataset": tf.data.Dataset.from_tensor_slices({"X":df_x,"Y":df_y}) \ }) ''' Initializes the SOM graph ''' def init_graph(self): #initial topology self.g = ig.Graph() self.g.add_vertices(self.N1*self.N2) incr = [(0,1),(0,-1),(1,0),(-1,0)] def isvalid(x): return(x[0] >= 0 and x[0] < self.N1 and\ x[1] >= 0 and x[1] < self.N2) def toOneDim(x): return x[0]*self.N2 + x[1] def sum_tuple(x,y): return(tuple(sum(pair) for pair in zip(x,y))) edges = [] #Add edges for i in np.arange(self.N1): for j in np.arange(self.N2): curr = (i,j) self.g.vs[toOneDim(curr)]["i"] = i self.g.vs[toOneDim(curr)]["j"] = j if self.gridmode.name == "RECTANGLE": incr = [(0,1),(0,-1),(1,0),(-1,0)] else: if i % 2 == 0: incr = [(0,1),(0,-1),(-1,-1),(-1,0),(1,-1),(1,0)] else: incr = [(0,1),(0,-1),(-1,1),(-1,0),(1,1),(1,0)] nbors = list(map(lambda x: sum_tuple(x,curr),incr)) nbors_exist = list(map(lambda x: isvalid(x),nbors)) for n in np.arange(len(nbors)): if nbors_exist[n]: edges += [(toOneDim(curr), toOneDim(nbors[n]))] print(str(curr) + "->" + str(nbors[n]) ) self.g.add_edges(edges) self.g.es["age"] = 0 #self.ID: maps index of each node to its corresponding position tuple (line, col) self.ID = np.array(list(map(lambda x: [self.g.vs[x]["i"],self.g.vs[x]["j"]],\ np.arange(self.N1*self.N2))),dtype=np.int32 ) self.ID = np.reshape(self.ID,(-1,2)) #Initialize distances print("Calculating distances...") self.D = np.array(self.g.shortest_paths(source=None, target=None, weights=None, mode=ig.ALL),dtype=np.int32) print("Done!") def build_model(self): X = self.X_placeholder W = self.W_placeholder nsize = self.nborhood_size_placeholder sigma = self.sigma_placeholder eps = self.eps_placeholder #Step 3: Calculate dist_vecs (vector and magnitude) self.dist_vecs = tf.map_fn(lambda w: X - w,W) self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W) #Step 4:Calculate 2 best self.s = tf.math.top_k(-self.squared_distances,k=2) #1D Index of s1_2d,s2_2d self.s1_1d = self.s.indices[0] self.s2_1d = self.s.indices[1] #2d Index of s1_2d,s2_2d self.s1_2d = tf.gather(self.ID,self.s1_1d) self.s2_2d = tf.gather(self.ID,self.s2_1d) #Step 5: Calculate l1 distances #self.l1 = tf.map_fn(lambda x: tf.norm(x-self.s1_2d,ord=1),self.ID) self.l1 = tf.gather(self.D,self.s1_1d) self.mask = tf.reshape(tf.where(self.l1 <= nsize),\ tf.convert_to_tensor([-1])) #Step 6: Calculate neighborhood function values if self.ntype.name == "GAUSSIAN": self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\ /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\ y=tf.zeros(self.l1.shape)), tf.convert_to_tensor([-1])) else: raise ValueError("unknown self.ntype") #Step 6: Update W self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs) def cycle(self, current_iter, mode = Mode["TRAIN"]): nxt = self.sess.run(self.iter_next)["X"] if mode.name == "TRAIN": #Iteration numbers as floats current_iter_f = float(current_iter) n_iter_f = float(self.n_iter) #Get current epsilon and theta eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f) sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f) print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps)) #Get vector distance, square distance self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) self.s1_1d = np.argmin(self.squared_distances,axis=-1) self.s1_2d = self.ID[self.s1_1d] #Get L1 distances #self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID))) self.l1 = self.D[self.s1_1d,:] self.mask = np.reshape(np.where(self.l1 <= sigma),[-1]) if self.ntype.name == "GAUSSIAN": squared_l1 = np.square(self.l1.astype(np.float32)) self.h = np.exp(-squared_l1 /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1]) for i in np.arange(self.N1*self.N2): self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:] elif mode.name == "TEST": self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) #Get first and second activation top_2 = np.argsort(self.squared_distances)[0:2] self.s1_1d = top_2[0] self.s2_1d = top_2[1] self.s1_2d = self.ID[self.s1_1d] self.s2_2d = self.ID[self.s2_1d] #Get topographic error if (self.s2_1d in self.g.neighbors(self.s1_1d)): topographic_error = 0 else: topographic_error = 1 #print("ERROR {}-{};{}-{}".format(self.s1_2d,self.squared_distances[self.s1_1d],\ # self.s2_2d,self.squared_distances[self.s2_1d] )) #Get quantization error quantization_error = (self.squared_distances[self.s1_1d]) return ({"topographic_error":topographic_error,\ "quantization_error":quantization_error}) def train(self): #Run initializer self.sess.run(self.init) self.sess.run(self.iterator_ds.initializer) if self.initmode.name == "PCAINIT": if self.ds_inputdim < 2: raise ValueError("uniform init needs dim input >= 2") self.W = np.zeros([self.N1*self.N2,3]) print(self.W.shape) self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2]) if self.gridmode.name == "HEXAGON": print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))) self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\ ,1] -= 0.5 print(self.W.shape) self.W = np.matmul(self.W,self.pca.components_) print(self.W.shape) self.W = StandardScaler().fit_transform(self.W) print(self.W.shape) else: self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\ dtype=tf.float32)) self.W = StandardScaler().fit_transform(self.W) #BEGIN Training for current_iter in np.arange(self.n_iter): self.cycle(current_iter) if current_iter % self.plot_iter == 0: self.prettygraph(current_iter,mask=self.mask) self.prettygraph(self.n_iter,mask=self.mask,online=True) #END Training #BEGIN Testing self.sess.run(self.iterator_ds.initializer) topographic_error = 0 quantization_error = 0 chosen_Mat = np.zeros((self.N1,self.N2)) for current_iter in np.arange(self.ds_size): cycl = self.cycle(current_iter,mode=Mode["TEST"]) topographic_error += cycl["topographic_error"] quantization_error += cycl["quantization_error"] chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1 topographic_error = topographic_error / self.ds_size quantization_error = quantization_error / self.ds_size #Generate U-Matrix U_Mat = np.zeros((self.N1,self.N2)) for i in np.arange(self.N1): for j in np.arange(self.N2): vert_pos = self.W[i * self.N2 + j] nbors = self.g.neighbors(i * self.N2 + j) d = np.sum(\ list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\ ,nbors))) U_Mat[i,j] = d print("Quantization Error:{}".format(quantization_error)) print("Topographic Error:{}".format(topographic_error)) print(np.array(self.characteristics_dict.keys()) ) df_keys = list(self.characteristics_dict.keys()) +\ ["quantization_error","topographic_error"] df_vals = list(self.characteristics_dict.values()) +\ [quantization_error,topographic_error] #df_vals = [str(x) for x in df_vals] print(df_keys) print(df_vals) print(len(df_keys)) print(len(df_vals)) if os.path.exists("runs.csv"): print("CSV exists") df = pd.read_csv("runs.csv",header=0) df_new = pd.DataFrame(columns=df_keys,index=np.arange(1)) df_new.iloc[0,:] = df_vals df = df.append(df_new,ignore_index=True) else: print("CSV created") df = pd.DataFrame(columns=df_keys,index=np.arange(1)) df.iloc[0,:] = df_vals df.to_csv("runs.csv",index=False) def inputScatter3D(self): Xn = self.input_pca[:,0] Yn = self.input_pca[:,1] Zn = self.input_pca[:,2] Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) ) Y = [int(x) for x in Y] num_class = len(Y) pal = ig.ClusterColoringPalette(num_class) if self.plotmode.name == "CLASS_COLOR": col = pal.get_many(Y) siz = 2 else: col = "green" siz = 1.5 trace0=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='input', marker=dict(symbol='circle', size=siz, color=col, line=dict(color='rgb(50,50,50)', width=0.25) ), text="", hoverinfo='text' ) return(trace0) def prettygraph(self,iter_number, mask,online = False): trace0 = self.input_pca_scatter W = self.pca.transform(self.W) Xn=W[:,0]# x-coordinates of nodes Yn=W[:,1] # y-coordinates if self.ds_name in ["box","grid"]: Zn=self.W[:,2] # z-coordinates else: Zn=W[:,2] # z-coordinates edge_colors = [] Xe=[] Ye=[] Ze=[] num_pallete = 1000 for e in self.g.get_edgelist(): #col = self.g.es.find(_between=((e[0],), (e[1],)),)["age"] #col = float(col)/float(1) #col = min(num_pallete-1, int(num_pallete * col)) #edge_colors += [col,col] Xe+=[W[e[0],0],W[e[1],0],None]# x-coordinates of edge ends Ye+=[W[e[0],1],W[e[1],1],None]# y-coordinates of edge ends Ze+=[W[e[0],2],W[e[1],2],None]# z-coordinates of edge ends #Create Scaling for edges based on Age pal_V = ig.GradientPalette("blue", "black", num_pallete) pal_E = ig.GradientPalette("black", "white", num_pallete) v_colors = ["orange" for a in np.arange(self.g.vcount())] for v in mask: v_colors[v] = "yellow" trace1=go.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=dict(color="black", width=3), hoverinfo='none' ) reference_vec_text = ["m" + str(x) for x in np.arange(self.W.shape[0])] trace2=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='reference_vectors', marker=dict(symbol='square', size=6, color=v_colors, line=dict(color='rgb(50,50,50)', width=0.5) ), text=reference_vec_text, hoverinfo='text' ) axis=dict(showbackground=False, showline=True, zeroline=False, showgrid=False, showticklabels=True, title='', range = [-self.input_pca_maxval-1,1+self.input_pca_maxval] ) layout = go.Layout( title="Visualization of SOM", width=1000, height=1000, showlegend=False, scene=dict( xaxis=dict(axis), yaxis=dict(axis), zaxis=dict(axis), ), margin=dict( t=100 ), hovermode='closest', annotations=[ dict( showarrow=False, text="Data source:</a>", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=dict( size=14 ) ) ], ) data=[trace1, trace2, trace0] fig=go.Figure(data=data, layout=layout) OUTPATH = "./plot/" for k, v in sorted(zip(self.characteristics_dict.keys(),self.characteristics_dict.values()),key = lambda t: (t[0].lower()) ):
OUTPATH = OUTPATH[0:(len(OUTPATH) - 1)] if not os.path.exists(OUTPATH): os.mkdir(OUTPATH) print("Plotting graph...") if online: try: py.iplot(fig) except plotly.exceptions.PlotlyRequestError: print("Warning: Could not plot online") pio.write_image(fig,OUTPATH + "/" + str(iter_number) + ".png") print("Done!")
OUTPATH += str(k)+ "=" + str(v) + ";"
conditional_block
som.py
import get_datasets as gd import os import time from glob import glob import tensorflow as tf import numpy as np from collections import namedtuple import re #PANDAS from pandas.core.frame import DataFrame import pandas as pd import igraph as ig from enum import Enum #SKLEARN from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA #PLOTLY import plotly.tools import plotly.plotly as py import plotly.io as pio import plotly.graph_objs as go from asn1crypto.core import InstanceOf import sklearn import os plotly.tools.set_credentials_file(username='isonettv', api_key='2Lg1USMkZAHONqo82eMG') ''' The mode used in a cycle. Can be one of: TRAIN: to use when training the model TEST: to use when testing the model ''' Mode = Enum("Mode","TRAIN TEST PRED") ''' Neighborhood function h_ij to be used. Can be one of: GAUSSIAN: Uses a gaussian with decay equal to self.sigma on the neighborhood CONSTANT: 1 if in neighborhood, 0 otherwise ''' NFunc = Enum("NFunc","GAUSSIAN CONSTANT") ''' Initialization of the initial points.Can be one of: RANDOM: Initializes each points randomly inside (-self.init_maxval,+self.init_maxval) PCAINIT: Uses the 2 principal components to unfold a grid ''' InitMode = Enum("InitMode","RANDOM PCAINIT") ''' Configuration for the plot operation.Can be one of: CLASS_COLOR: Shows the class attr. of unlabeled points through color CLASS_NOCOLOR: All unlabeled points have the same color ''' PlotMode = Enum("PlotMode","CLASS_COLOR CLASS_NOCOLOR") ''' Configuration for grid type. Can be one of: RECTANGLE: Use rectangular grid HEXAGON: Use hexagonal grid ''' GridMode = Enum("GridMode","RECTANGLE HEXAGON") class som(object): ''' Creates a Self-Organizing Map (SOM). It has a couple of parameters to be selected by using the "args" object. These include: self.N1: Number of nodes in each row of the grid self.N2: Number of nodes in each column of the grid self.eps_i, self.eps_f: initial and final values of epsilon. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.sigma_i, self.sigma_f: initial and final values of sigma. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.ntype: Neighborhood type self.plotmode: which plot to make self.initmode: how to initialize grid self.gridmode: which type of grid self.ds_name: Name of dataset (iris,isolet,wine,grid) ''' ''' Initializes the Growing Neural Gas Network @param sess: the current session @param args: object containing arguments (see main.py) ''' def __init__(self, sess, args): # Parameters self.sess = sess self.run_id = args.run_id #Number of nodes in each row of the grid self.N1 = args.n1 #Number of nodes in each column of the grid self.N2 = args.n2 #Initial and final values of epsilon self.eps_i = args.eps_i self.eps_f = args.eps_f #Initial and final values of sigma self.sigma_i = args.sigma_i self.sigma_f = args.sigma_f #Neighborhood type self.ntype = NFunc[args.ntype] #Which plot to make self.plotmode = PlotMode[args.plotmode] #Grid Mode self.gridmode = GridMode[args.gridmode] self.nsize = 1 #Which way to initialize points self.initmode = InitMode[args.initmode] #dataset chosen self.ds_name = args.dataset #Total number of iterations self.n_iter = args.n_iter #Number of iterations between plot op self.plot_iter = args.plot_iter self.characteristics_dict = \ {"dataset":str(self.ds_name), "num_iter":self.n_iter, "n1":self.N1, "n2":self.N2, "eps_i":self.eps_i, "eps_f":self.eps_f, "sigma_i":self.sigma_i, "ntype":self.ntype.name, "initmode":self.initmode.name, "gridmode":self.gridmode.name, "run_id":self.run_id } #Get datasets if args.dataset == "isolet": temp = gd.get_isolet(test_subset= args.cv) elif args.dataset == "iris": temp = gd.get_iris(args.cv) elif args.dataset == "wine": temp = gd.get_wine(args.cv) elif args.dataset == "grid" or args.dataset == "box": temp = gd.get_grid() else: raise ValueError("Bad dataset name") #Create Dataset if isinstance(temp,dict) and 'train' in temp.keys(): self.ds = temp["train"].concatenate(temp["test"]) else: self.ds = temp #Store number of dataset elements and input dimension self.ds_size = self.getNumElementsOfDataset(self.ds) self.ds_inputdim = self.getInputShapeOfDataset(self.ds) #Normalize dataset temp = self.normalizedDataset(self.ds) self.ds = temp["dataset"] df_x_normalized = temp["df_x"] self.Y = temp["df_y"] #Get PCA for dataset print("Generating PCA for further plotting...") self.pca = PCA(n_components=3) self.input_pca = self.pca.fit_transform(df_x_normalized) self.input_pca_scatter = self.inputScatter3D() self.input_pca_maxval = -np.sort(-np.abs(np.reshape(self.input_pca,[-1])),axis=0)[5] print("Done!") print("Dimensionality of Y:{}",self.ds_inputdim) self.ds = self.ds.shuffle(buffer_size=10000).repeat() if args.dataset == "box": self.ds = gd.get_box() #Now generate iterators for dataset self.iterator_ds = self.ds.make_initializable_iterator() self.iter_next = self.iterator_ds.get_next() # tf Graph input self.X_placeholder = tf.placeholder("float", [self.ds_inputdim]) self.W_placeholder = tf.placeholder("float", [self.N1*self.N2,self.ds_inputdim]) self.nborhood_size_placeholder = tf.placeholder("int32", []) self.sigma_placeholder = tf.placeholder("float", []) self.eps_placeholder = tf.placeholder("float", []) print("Initializing graph and global vars...") self.init_graph() # Initializing the variables self.init = tf.global_variables_initializer() print("Done!") ''' Transforms dataset back to dataframe''' def getDatasetAsDF(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break return({"df_x":df_x,"df_y":df_y}) ''' Returns the total number of elements of a dataset @param dataset: the given dataset @return: total number of elements ''' def getNumElementsOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: self.sess.run(next_element) num_elems += 1 except tf.errors.OutOfRangeError: break return num_elems ''' Returns the dimensionality of the first element of dataset @param dataset: the given dataset @return: total number of elements ''' def getInputShapeOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() d = None try: self.sess.run(next_element) d = next_element["X"].shape[0] except tf.errors.OutOfRangeError: return d return int(d) ''' Returns the normalized version of a given dataset @param dataset: the given dataset, such that each element returns an "X" and "Y" @return: dict, with keys "df_x": normalized elements, "df_y": corresponding class attr., "dataset": normalized dataset ("X" and "Y") ''' def normalizedDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break df_x = StandardScaler().fit_transform(df_x) print(df_y) return({"df_x": df_x, "df_y": df_y, "dataset": tf.data.Dataset.from_tensor_slices({"X":df_x,"Y":df_y}) \ }) ''' Initializes the SOM graph ''' def init_graph(self): #initial topology self.g = ig.Graph() self.g.add_vertices(self.N1*self.N2) incr = [(0,1),(0,-1),(1,0),(-1,0)] def isvalid(x): return(x[0] >= 0 and x[0] < self.N1 and\ x[1] >= 0 and x[1] < self.N2) def toOneDim(x): return x[0]*self.N2 + x[1] def sum_tuple(x,y): return(tuple(sum(pair) for pair in zip(x,y))) edges = [] #Add edges for i in np.arange(self.N1): for j in np.arange(self.N2): curr = (i,j) self.g.vs[toOneDim(curr)]["i"] = i self.g.vs[toOneDim(curr)]["j"] = j if self.gridmode.name == "RECTANGLE": incr = [(0,1),(0,-1),(1,0),(-1,0)] else: if i % 2 == 0: incr = [(0,1),(0,-1),(-1,-1),(-1,0),(1,-1),(1,0)] else: incr = [(0,1),(0,-1),(-1,1),(-1,0),(1,1),(1,0)] nbors = list(map(lambda x: sum_tuple(x,curr),incr)) nbors_exist = list(map(lambda x: isvalid(x),nbors)) for n in np.arange(len(nbors)): if nbors_exist[n]: edges += [(toOneDim(curr), toOneDim(nbors[n]))] print(str(curr) + "->" + str(nbors[n]) ) self.g.add_edges(edges) self.g.es["age"] = 0 #self.ID: maps index of each node to its corresponding position tuple (line, col) self.ID = np.array(list(map(lambda x: [self.g.vs[x]["i"],self.g.vs[x]["j"]],\ np.arange(self.N1*self.N2))),dtype=np.int32 ) self.ID = np.reshape(self.ID,(-1,2)) #Initialize distances print("Calculating distances...") self.D = np.array(self.g.shortest_paths(source=None, target=None, weights=None, mode=ig.ALL),dtype=np.int32) print("Done!") def build_model(self): X = self.X_placeholder W = self.W_placeholder nsize = self.nborhood_size_placeholder sigma = self.sigma_placeholder eps = self.eps_placeholder #Step 3: Calculate dist_vecs (vector and magnitude) self.dist_vecs = tf.map_fn(lambda w: X - w,W) self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W) #Step 4:Calculate 2 best self.s = tf.math.top_k(-self.squared_distances,k=2) #1D Index of s1_2d,s2_2d self.s1_1d = self.s.indices[0] self.s2_1d = self.s.indices[1] #2d Index of s1_2d,s2_2d self.s1_2d = tf.gather(self.ID,self.s1_1d) self.s2_2d = tf.gather(self.ID,self.s2_1d) #Step 5: Calculate l1 distances #self.l1 = tf.map_fn(lambda x: tf.norm(x-self.s1_2d,ord=1),self.ID) self.l1 = tf.gather(self.D,self.s1_1d) self.mask = tf.reshape(tf.where(self.l1 <= nsize),\ tf.convert_to_tensor([-1])) #Step 6: Calculate neighborhood function values if self.ntype.name == "GAUSSIAN": self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\ /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\ y=tf.zeros(self.l1.shape)), tf.convert_to_tensor([-1])) else: raise ValueError("unknown self.ntype") #Step 6: Update W self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs) def cycle(self, current_iter, mode = Mode["TRAIN"]): nxt = self.sess.run(self.iter_next)["X"] if mode.name == "TRAIN": #Iteration numbers as floats current_iter_f = float(current_iter) n_iter_f = float(self.n_iter) #Get current epsilon and theta eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f) sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f) print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps)) #Get vector distance, square distance self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) self.s1_1d = np.argmin(self.squared_distances,axis=-1) self.s1_2d = self.ID[self.s1_1d] #Get L1 distances #self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID))) self.l1 = self.D[self.s1_1d,:] self.mask = np.reshape(np.where(self.l1 <= sigma),[-1]) if self.ntype.name == "GAUSSIAN": squared_l1 = np.square(self.l1.astype(np.float32)) self.h = np.exp(-squared_l1 /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1]) for i in np.arange(self.N1*self.N2): self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:] elif mode.name == "TEST": self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) #Get first and second activation top_2 = np.argsort(self.squared_distances)[0:2] self.s1_1d = top_2[0] self.s2_1d = top_2[1] self.s1_2d = self.ID[self.s1_1d] self.s2_2d = self.ID[self.s2_1d] #Get topographic error if (self.s2_1d in self.g.neighbors(self.s1_1d)): topographic_error = 0 else: topographic_error = 1 #print("ERROR {}-{};{}-{}".format(self.s1_2d,self.squared_distances[self.s1_1d],\ # self.s2_2d,self.squared_distances[self.s2_1d] )) #Get quantization error quantization_error = (self.squared_distances[self.s1_1d]) return ({"topographic_error":topographic_error,\ "quantization_error":quantization_error}) def train(self): #Run initializer self.sess.run(self.init) self.sess.run(self.iterator_ds.initializer) if self.initmode.name == "PCAINIT": if self.ds_inputdim < 2: raise ValueError("uniform init needs dim input >= 2") self.W = np.zeros([self.N1*self.N2,3]) print(self.W.shape) self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2]) if self.gridmode.name == "HEXAGON": print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))) self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\ ,1] -= 0.5 print(self.W.shape) self.W = np.matmul(self.W,self.pca.components_) print(self.W.shape) self.W = StandardScaler().fit_transform(self.W) print(self.W.shape) else: self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\ dtype=tf.float32)) self.W = StandardScaler().fit_transform(self.W) #BEGIN Training for current_iter in np.arange(self.n_iter): self.cycle(current_iter) if current_iter % self.plot_iter == 0: self.prettygraph(current_iter,mask=self.mask) self.prettygraph(self.n_iter,mask=self.mask,online=True) #END Training #BEGIN Testing self.sess.run(self.iterator_ds.initializer) topographic_error = 0 quantization_error = 0 chosen_Mat = np.zeros((self.N1,self.N2)) for current_iter in np.arange(self.ds_size): cycl = self.cycle(current_iter,mode=Mode["TEST"]) topographic_error += cycl["topographic_error"] quantization_error += cycl["quantization_error"] chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1 topographic_error = topographic_error / self.ds_size quantization_error = quantization_error / self.ds_size #Generate U-Matrix U_Mat = np.zeros((self.N1,self.N2)) for i in np.arange(self.N1): for j in np.arange(self.N2): vert_pos = self.W[i * self.N2 + j] nbors = self.g.neighbors(i * self.N2 + j) d = np.sum(\ list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\ ,nbors))) U_Mat[i,j] = d print("Quantization Error:{}".format(quantization_error)) print("Topographic Error:{}".format(topographic_error)) print(np.array(self.characteristics_dict.keys()) ) df_keys = list(self.characteristics_dict.keys()) +\ ["quantization_error","topographic_error"] df_vals = list(self.characteristics_dict.values()) +\ [quantization_error,topographic_error] #df_vals = [str(x) for x in df_vals] print(df_keys) print(df_vals) print(len(df_keys)) print(len(df_vals)) if os.path.exists("runs.csv"): print("CSV exists") df = pd.read_csv("runs.csv",header=0) df_new = pd.DataFrame(columns=df_keys,index=np.arange(1)) df_new.iloc[0,:] = df_vals df = df.append(df_new,ignore_index=True) else: print("CSV created") df = pd.DataFrame(columns=df_keys,index=np.arange(1)) df.iloc[0,:] = df_vals df.to_csv("runs.csv",index=False) def inputScatter3D(self): Xn = self.input_pca[:,0] Yn = self.input_pca[:,1] Zn = self.input_pca[:,2] Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) ) Y = [int(x) for x in Y] num_class = len(Y) pal = ig.ClusterColoringPalette(num_class) if self.plotmode.name == "CLASS_COLOR": col = pal.get_many(Y) siz = 2 else: col = "green" siz = 1.5 trace0=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='input', marker=dict(symbol='circle', size=siz, color=col, line=dict(color='rgb(50,50,50)', width=0.25) ), text="", hoverinfo='text' ) return(trace0) def prettygraph(self,iter_number, mask,online = False):
Xn=W[:,0]# x-coordinates of nodes Yn=W[:,1] # y-coordinates if self.ds_name in ["box","grid"]: Zn=self.W[:,2] # z-coordinates else: Zn=W[:,2] # z-coordinates edge_colors = [] Xe=[] Ye=[] Ze=[] num_pallete = 1000 for e in self.g.get_edgelist(): #col = self.g.es.find(_between=((e[0],), (e[1],)),)["age"] #col = float(col)/float(1) #col = min(num_pallete-1, int(num_pallete * col)) #edge_colors += [col,col] Xe+=[W[e[0],0],W[e[1],0],None]# x-coordinates of edge ends Ye+=[W[e[0],1],W[e[1],1],None]# y-coordinates of edge ends Ze+=[W[e[0],2],W[e[1],2],None]# z-coordinates of edge ends #Create Scaling for edges based on Age pal_V = ig.GradientPalette("blue", "black", num_pallete) pal_E = ig.GradientPalette("black", "white", num_pallete) v_colors = ["orange" for a in np.arange(self.g.vcount())] for v in mask: v_colors[v] = "yellow" trace1=go.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=dict(color="black", width=3), hoverinfo='none' ) reference_vec_text = ["m" + str(x) for x in np.arange(self.W.shape[0])] trace2=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='reference_vectors', marker=dict(symbol='square', size=6, color=v_colors, line=dict(color='rgb(50,50,50)', width=0.5) ), text=reference_vec_text, hoverinfo='text' ) axis=dict(showbackground=False, showline=True, zeroline=False, showgrid=False, showticklabels=True, title='', range = [-self.input_pca_maxval-1,1+self.input_pca_maxval] ) layout = go.Layout( title="Visualization of SOM", width=1000, height=1000, showlegend=False, scene=dict( xaxis=dict(axis), yaxis=dict(axis), zaxis=dict(axis), ), margin=dict( t=100 ), hovermode='closest', annotations=[ dict( showarrow=False, text="Data source:</a>", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=dict( size=14 ) ) ], ) data=[trace1, trace2, trace0] fig=go.Figure(data=data, layout=layout) OUTPATH = "./plot/" for k, v in sorted(zip(self.characteristics_dict.keys(),self.characteristics_dict.values()),key = lambda t: (t[0].lower()) ): OUTPATH += str(k)+ "=" + str(v) + ";" OUTPATH = OUTPATH[0:(len(OUTPATH) - 1)] if not os.path.exists(OUTPATH): os.mkdir(OUTPATH) print("Plotting graph...") if online: try: py.iplot(fig) except plotly.exceptions.PlotlyRequestError: print("Warning: Could not plot online") pio.write_image(fig,OUTPATH + "/" + str(iter_number) + ".png") print("Done!")
trace0 = self.input_pca_scatter W = self.pca.transform(self.W)
random_line_split
som.py
import get_datasets as gd import os import time from glob import glob import tensorflow as tf import numpy as np from collections import namedtuple import re #PANDAS from pandas.core.frame import DataFrame import pandas as pd import igraph as ig from enum import Enum #SKLEARN from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA #PLOTLY import plotly.tools import plotly.plotly as py import plotly.io as pio import plotly.graph_objs as go from asn1crypto.core import InstanceOf import sklearn import os plotly.tools.set_credentials_file(username='isonettv', api_key='2Lg1USMkZAHONqo82eMG') ''' The mode used in a cycle. Can be one of: TRAIN: to use when training the model TEST: to use when testing the model ''' Mode = Enum("Mode","TRAIN TEST PRED") ''' Neighborhood function h_ij to be used. Can be one of: GAUSSIAN: Uses a gaussian with decay equal to self.sigma on the neighborhood CONSTANT: 1 if in neighborhood, 0 otherwise ''' NFunc = Enum("NFunc","GAUSSIAN CONSTANT") ''' Initialization of the initial points.Can be one of: RANDOM: Initializes each points randomly inside (-self.init_maxval,+self.init_maxval) PCAINIT: Uses the 2 principal components to unfold a grid ''' InitMode = Enum("InitMode","RANDOM PCAINIT") ''' Configuration for the plot operation.Can be one of: CLASS_COLOR: Shows the class attr. of unlabeled points through color CLASS_NOCOLOR: All unlabeled points have the same color ''' PlotMode = Enum("PlotMode","CLASS_COLOR CLASS_NOCOLOR") ''' Configuration for grid type. Can be one of: RECTANGLE: Use rectangular grid HEXAGON: Use hexagonal grid ''' GridMode = Enum("GridMode","RECTANGLE HEXAGON") class som(object): ''' Creates a Self-Organizing Map (SOM). It has a couple of parameters to be selected by using the "args" object. These include: self.N1: Number of nodes in each row of the grid self.N2: Number of nodes in each column of the grid self.eps_i, self.eps_f: initial and final values of epsilon. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.sigma_i, self.sigma_f: initial and final values of sigma. The current value of epsilon is given by self.eps_i * (self.eps_f/self.eps_i)^p, where p is percent of completed iterations. self.ntype: Neighborhood type self.plotmode: which plot to make self.initmode: how to initialize grid self.gridmode: which type of grid self.ds_name: Name of dataset (iris,isolet,wine,grid) ''' ''' Initializes the Growing Neural Gas Network @param sess: the current session @param args: object containing arguments (see main.py) ''' def __init__(self, sess, args): # Parameters self.sess = sess self.run_id = args.run_id #Number of nodes in each row of the grid self.N1 = args.n1 #Number of nodes in each column of the grid self.N2 = args.n2 #Initial and final values of epsilon self.eps_i = args.eps_i self.eps_f = args.eps_f #Initial and final values of sigma self.sigma_i = args.sigma_i self.sigma_f = args.sigma_f #Neighborhood type self.ntype = NFunc[args.ntype] #Which plot to make self.plotmode = PlotMode[args.plotmode] #Grid Mode self.gridmode = GridMode[args.gridmode] self.nsize = 1 #Which way to initialize points self.initmode = InitMode[args.initmode] #dataset chosen self.ds_name = args.dataset #Total number of iterations self.n_iter = args.n_iter #Number of iterations between plot op self.plot_iter = args.plot_iter self.characteristics_dict = \ {"dataset":str(self.ds_name), "num_iter":self.n_iter, "n1":self.N1, "n2":self.N2, "eps_i":self.eps_i, "eps_f":self.eps_f, "sigma_i":self.sigma_i, "ntype":self.ntype.name, "initmode":self.initmode.name, "gridmode":self.gridmode.name, "run_id":self.run_id } #Get datasets if args.dataset == "isolet": temp = gd.get_isolet(test_subset= args.cv) elif args.dataset == "iris": temp = gd.get_iris(args.cv) elif args.dataset == "wine": temp = gd.get_wine(args.cv) elif args.dataset == "grid" or args.dataset == "box": temp = gd.get_grid() else: raise ValueError("Bad dataset name") #Create Dataset if isinstance(temp,dict) and 'train' in temp.keys(): self.ds = temp["train"].concatenate(temp["test"]) else: self.ds = temp #Store number of dataset elements and input dimension self.ds_size = self.getNumElementsOfDataset(self.ds) self.ds_inputdim = self.getInputShapeOfDataset(self.ds) #Normalize dataset temp = self.normalizedDataset(self.ds) self.ds = temp["dataset"] df_x_normalized = temp["df_x"] self.Y = temp["df_y"] #Get PCA for dataset print("Generating PCA for further plotting...") self.pca = PCA(n_components=3) self.input_pca = self.pca.fit_transform(df_x_normalized) self.input_pca_scatter = self.inputScatter3D() self.input_pca_maxval = -np.sort(-np.abs(np.reshape(self.input_pca,[-1])),axis=0)[5] print("Done!") print("Dimensionality of Y:{}",self.ds_inputdim) self.ds = self.ds.shuffle(buffer_size=10000).repeat() if args.dataset == "box": self.ds = gd.get_box() #Now generate iterators for dataset self.iterator_ds = self.ds.make_initializable_iterator() self.iter_next = self.iterator_ds.get_next() # tf Graph input self.X_placeholder = tf.placeholder("float", [self.ds_inputdim]) self.W_placeholder = tf.placeholder("float", [self.N1*self.N2,self.ds_inputdim]) self.nborhood_size_placeholder = tf.placeholder("int32", []) self.sigma_placeholder = tf.placeholder("float", []) self.eps_placeholder = tf.placeholder("float", []) print("Initializing graph and global vars...") self.init_graph() # Initializing the variables self.init = tf.global_variables_initializer() print("Done!") ''' Transforms dataset back to dataframe''' def getDatasetAsDF(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break return({"df_x":df_x,"df_y":df_y}) ''' Returns the total number of elements of a dataset @param dataset: the given dataset @return: total number of elements ''' def getNumElementsOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: self.sess.run(next_element) num_elems += 1 except tf.errors.OutOfRangeError: break return num_elems ''' Returns the dimensionality of the first element of dataset @param dataset: the given dataset @return: total number of elements ''' def getInputShapeOfDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() d = None try: self.sess.run(next_element) d = next_element["X"].shape[0] except tf.errors.OutOfRangeError: return d return int(d) ''' Returns the normalized version of a given dataset @param dataset: the given dataset, such that each element returns an "X" and "Y" @return: dict, with keys "df_x": normalized elements, "df_y": corresponding class attr., "dataset": normalized dataset ("X" and "Y") ''' def normalizedDataset(self,dataset): iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() num_elems = 0 while True: try: x, y = self.sess.run([next_element["X"], next_element["Y"]]) if num_elems == 0: df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(x.shape[0]) ) print(y) df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\ columns = np.arange(y.shape[0]) ) df_x.iloc[num_elems,:] = x df_y.iloc[num_elems,:] = y num_elems += 1 except tf.errors.OutOfRangeError: break df_x = StandardScaler().fit_transform(df_x) print(df_y) return({"df_x": df_x, "df_y": df_y, "dataset": tf.data.Dataset.from_tensor_slices({"X":df_x,"Y":df_y}) \ }) ''' Initializes the SOM graph ''' def init_graph(self): #initial topology self.g = ig.Graph() self.g.add_vertices(self.N1*self.N2) incr = [(0,1),(0,-1),(1,0),(-1,0)] def isvalid(x):
def toOneDim(x): return x[0]*self.N2 + x[1] def sum_tuple(x,y): return(tuple(sum(pair) for pair in zip(x,y))) edges = [] #Add edges for i in np.arange(self.N1): for j in np.arange(self.N2): curr = (i,j) self.g.vs[toOneDim(curr)]["i"] = i self.g.vs[toOneDim(curr)]["j"] = j if self.gridmode.name == "RECTANGLE": incr = [(0,1),(0,-1),(1,0),(-1,0)] else: if i % 2 == 0: incr = [(0,1),(0,-1),(-1,-1),(-1,0),(1,-1),(1,0)] else: incr = [(0,1),(0,-1),(-1,1),(-1,0),(1,1),(1,0)] nbors = list(map(lambda x: sum_tuple(x,curr),incr)) nbors_exist = list(map(lambda x: isvalid(x),nbors)) for n in np.arange(len(nbors)): if nbors_exist[n]: edges += [(toOneDim(curr), toOneDim(nbors[n]))] print(str(curr) + "->" + str(nbors[n]) ) self.g.add_edges(edges) self.g.es["age"] = 0 #self.ID: maps index of each node to its corresponding position tuple (line, col) self.ID = np.array(list(map(lambda x: [self.g.vs[x]["i"],self.g.vs[x]["j"]],\ np.arange(self.N1*self.N2))),dtype=np.int32 ) self.ID = np.reshape(self.ID,(-1,2)) #Initialize distances print("Calculating distances...") self.D = np.array(self.g.shortest_paths(source=None, target=None, weights=None, mode=ig.ALL),dtype=np.int32) print("Done!") def build_model(self): X = self.X_placeholder W = self.W_placeholder nsize = self.nborhood_size_placeholder sigma = self.sigma_placeholder eps = self.eps_placeholder #Step 3: Calculate dist_vecs (vector and magnitude) self.dist_vecs = tf.map_fn(lambda w: X - w,W) self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W) #Step 4:Calculate 2 best self.s = tf.math.top_k(-self.squared_distances,k=2) #1D Index of s1_2d,s2_2d self.s1_1d = self.s.indices[0] self.s2_1d = self.s.indices[1] #2d Index of s1_2d,s2_2d self.s1_2d = tf.gather(self.ID,self.s1_1d) self.s2_2d = tf.gather(self.ID,self.s2_1d) #Step 5: Calculate l1 distances #self.l1 = tf.map_fn(lambda x: tf.norm(x-self.s1_2d,ord=1),self.ID) self.l1 = tf.gather(self.D,self.s1_1d) self.mask = tf.reshape(tf.where(self.l1 <= nsize),\ tf.convert_to_tensor([-1])) #Step 6: Calculate neighborhood function values if self.ntype.name == "GAUSSIAN": self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\ /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\ y=tf.zeros(self.l1.shape)), tf.convert_to_tensor([-1])) else: raise ValueError("unknown self.ntype") #Step 6: Update W self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs) def cycle(self, current_iter, mode = Mode["TRAIN"]): nxt = self.sess.run(self.iter_next)["X"] if mode.name == "TRAIN": #Iteration numbers as floats current_iter_f = float(current_iter) n_iter_f = float(self.n_iter) #Get current epsilon and theta eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f) sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f) print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps)) #Get vector distance, square distance self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) self.s1_1d = np.argmin(self.squared_distances,axis=-1) self.s1_2d = self.ID[self.s1_1d] #Get L1 distances #self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID))) self.l1 = self.D[self.s1_1d,:] self.mask = np.reshape(np.where(self.l1 <= sigma),[-1]) if self.ntype.name == "GAUSSIAN": squared_l1 = np.square(self.l1.astype(np.float32)) self.h = np.exp(-squared_l1 /(2.0*sigma*sigma)) elif self.ntype.name == "CONSTANT": self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1]) for i in np.arange(self.N1*self.N2): self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:] elif mode.name == "TEST": self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W))) self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W))) #Get first and second activation top_2 = np.argsort(self.squared_distances)[0:2] self.s1_1d = top_2[0] self.s2_1d = top_2[1] self.s1_2d = self.ID[self.s1_1d] self.s2_2d = self.ID[self.s2_1d] #Get topographic error if (self.s2_1d in self.g.neighbors(self.s1_1d)): topographic_error = 0 else: topographic_error = 1 #print("ERROR {}-{};{}-{}".format(self.s1_2d,self.squared_distances[self.s1_1d],\ # self.s2_2d,self.squared_distances[self.s2_1d] )) #Get quantization error quantization_error = (self.squared_distances[self.s1_1d]) return ({"topographic_error":topographic_error,\ "quantization_error":quantization_error}) def train(self): #Run initializer self.sess.run(self.init) self.sess.run(self.iterator_ds.initializer) if self.initmode.name == "PCAINIT": if self.ds_inputdim < 2: raise ValueError("uniform init needs dim input >= 2") self.W = np.zeros([self.N1*self.N2,3]) print(self.W.shape) self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2]) if self.gridmode.name == "HEXAGON": print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))) self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\ ,1] -= 0.5 print(self.W.shape) self.W = np.matmul(self.W,self.pca.components_) print(self.W.shape) self.W = StandardScaler().fit_transform(self.W) print(self.W.shape) else: self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\ dtype=tf.float32)) self.W = StandardScaler().fit_transform(self.W) #BEGIN Training for current_iter in np.arange(self.n_iter): self.cycle(current_iter) if current_iter % self.plot_iter == 0: self.prettygraph(current_iter,mask=self.mask) self.prettygraph(self.n_iter,mask=self.mask,online=True) #END Training #BEGIN Testing self.sess.run(self.iterator_ds.initializer) topographic_error = 0 quantization_error = 0 chosen_Mat = np.zeros((self.N1,self.N2)) for current_iter in np.arange(self.ds_size): cycl = self.cycle(current_iter,mode=Mode["TEST"]) topographic_error += cycl["topographic_error"] quantization_error += cycl["quantization_error"] chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1 topographic_error = topographic_error / self.ds_size quantization_error = quantization_error / self.ds_size #Generate U-Matrix U_Mat = np.zeros((self.N1,self.N2)) for i in np.arange(self.N1): for j in np.arange(self.N2): vert_pos = self.W[i * self.N2 + j] nbors = self.g.neighbors(i * self.N2 + j) d = np.sum(\ list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\ ,nbors))) U_Mat[i,j] = d print("Quantization Error:{}".format(quantization_error)) print("Topographic Error:{}".format(topographic_error)) print(np.array(self.characteristics_dict.keys()) ) df_keys = list(self.characteristics_dict.keys()) +\ ["quantization_error","topographic_error"] df_vals = list(self.characteristics_dict.values()) +\ [quantization_error,topographic_error] #df_vals = [str(x) for x in df_vals] print(df_keys) print(df_vals) print(len(df_keys)) print(len(df_vals)) if os.path.exists("runs.csv"): print("CSV exists") df = pd.read_csv("runs.csv",header=0) df_new = pd.DataFrame(columns=df_keys,index=np.arange(1)) df_new.iloc[0,:] = df_vals df = df.append(df_new,ignore_index=True) else: print("CSV created") df = pd.DataFrame(columns=df_keys,index=np.arange(1)) df.iloc[0,:] = df_vals df.to_csv("runs.csv",index=False) def inputScatter3D(self): Xn = self.input_pca[:,0] Yn = self.input_pca[:,1] Zn = self.input_pca[:,2] Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) ) Y = [int(x) for x in Y] num_class = len(Y) pal = ig.ClusterColoringPalette(num_class) if self.plotmode.name == "CLASS_COLOR": col = pal.get_many(Y) siz = 2 else: col = "green" siz = 1.5 trace0=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='input', marker=dict(symbol='circle', size=siz, color=col, line=dict(color='rgb(50,50,50)', width=0.25) ), text="", hoverinfo='text' ) return(trace0) def prettygraph(self,iter_number, mask,online = False): trace0 = self.input_pca_scatter W = self.pca.transform(self.W) Xn=W[:,0]# x-coordinates of nodes Yn=W[:,1] # y-coordinates if self.ds_name in ["box","grid"]: Zn=self.W[:,2] # z-coordinates else: Zn=W[:,2] # z-coordinates edge_colors = [] Xe=[] Ye=[] Ze=[] num_pallete = 1000 for e in self.g.get_edgelist(): #col = self.g.es.find(_between=((e[0],), (e[1],)),)["age"] #col = float(col)/float(1) #col = min(num_pallete-1, int(num_pallete * col)) #edge_colors += [col,col] Xe+=[W[e[0],0],W[e[1],0],None]# x-coordinates of edge ends Ye+=[W[e[0],1],W[e[1],1],None]# y-coordinates of edge ends Ze+=[W[e[0],2],W[e[1],2],None]# z-coordinates of edge ends #Create Scaling for edges based on Age pal_V = ig.GradientPalette("blue", "black", num_pallete) pal_E = ig.GradientPalette("black", "white", num_pallete) v_colors = ["orange" for a in np.arange(self.g.vcount())] for v in mask: v_colors[v] = "yellow" trace1=go.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=dict(color="black", width=3), hoverinfo='none' ) reference_vec_text = ["m" + str(x) for x in np.arange(self.W.shape[0])] trace2=go.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='reference_vectors', marker=dict(symbol='square', size=6, color=v_colors, line=dict(color='rgb(50,50,50)', width=0.5) ), text=reference_vec_text, hoverinfo='text' ) axis=dict(showbackground=False, showline=True, zeroline=False, showgrid=False, showticklabels=True, title='', range = [-self.input_pca_maxval-1,1+self.input_pca_maxval] ) layout = go.Layout( title="Visualization of SOM", width=1000, height=1000, showlegend=False, scene=dict( xaxis=dict(axis), yaxis=dict(axis), zaxis=dict(axis), ), margin=dict( t=100 ), hovermode='closest', annotations=[ dict( showarrow=False, text="Data source:</a>", xref='paper', yref='paper', x=0, y=0.1, xanchor='left', yanchor='bottom', font=dict( size=14 ) ) ], ) data=[trace1, trace2, trace0] fig=go.Figure(data=data, layout=layout) OUTPATH = "./plot/" for k, v in sorted(zip(self.characteristics_dict.keys(),self.characteristics_dict.values()),key = lambda t: (t[0].lower()) ): OUTPATH += str(k)+ "=" + str(v) + ";" OUTPATH = OUTPATH[0:(len(OUTPATH) - 1)] if not os.path.exists(OUTPATH): os.mkdir(OUTPATH) print("Plotting graph...") if online: try: py.iplot(fig) except plotly.exceptions.PlotlyRequestError: print("Warning: Could not plot online") pio.write_image(fig,OUTPATH + "/" + str(iter_number) + ".png") print("Done!")
return(x[0] >= 0 and x[0] < self.N1 and\ x[1] >= 0 and x[1] < self.N2)
identifier_body
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursion_limit = "196"] mod generator; mod error; mod graph; mod util; mod leaf; use error::Error; use generator::Generator; use graph::{Graph, Fork, Rope}; use leaf::Leaf; use util::{Literal, Definition}; use proc_macro::TokenStream; use quote::quote; use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute}; use syn::spanned::Spanned; enum Mode { Utf8, Binary, } #[proc_macro_derive( Logos, attributes(logos, extras, error, end, token, regex, extras) )] pub fn logos(input: TokenStream) -> TokenStream
{ let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mode::Utf8; let mut errors = Vec::new(); let generics = match item.generics.params.len() { 0 => { None }, 1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => { Some(quote!(<'s>)) }, _ => { let span = item.generics.span(); errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span)); None } }; let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> { if attr.path.is_ident("logos") { if let Some(nested) = util::read_attr("logos", attr)? { let span = nested.span(); if let Some(ext) = util::value_from_nested("extras", &nested)? { if extras.replace(ext).is_some() { return Err(Error::new("Extras can be defined only once.").span(span)); } } if let Err(_) = util::value_from_nested("trivia", &nested) { const ERR: &str = "\ trivia are no longer supported.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(span)); } } } if attr.path.is_ident("extras") { const ERR: &str = "\ #[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(attr.span())); } Ok(()) }; for attr in &item.attrs { if let Err(err) = parse_attr(attr) { errors.push(err); } } let mut variants = Vec::new(); let mut ropes = Vec::new(); let mut regex_ids = Vec::new(); let mut graph = Graph::new(); for variant in &item.variants { variants.push(&variant.ident); let span = variant.span(); if let Some((_, value)) = &variant.discriminant { let span = value.span(); let value = util::unpack_int(value).unwrap_or(usize::max_value()); if value >= size { errors.push(Error::new( format!( "Discriminant value for `{}` is invalid. Expected integer in range 0..={}.", variant.ident, size, ), ).span(span)); } } let field = match &variant.fields { Fields::Unit => None, Fields::Unnamed(ref fields) => { if fields.unnamed.len() != 1 { errors.push(Error::new( format!( "Logos currently only supports variants with one field, found {}", fields.unnamed.len(), ) ).span(fields.span())) } let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone(); Some(field) } Fields::Named(_) => { errors.push(Error::new("Logos doesn't support named fields yet.").span(span)); None } }; for attr in &variant.attrs { let variant = &variant.ident; let mut with_definition = |definition: Definition<Literal>| { if let Literal::Bytes(..) = definition.value { mode = Mode::Binary; } ( Leaf::token(variant).field(field.clone()).callback(definition.callback), definition.value, ) }; if attr.path.is_ident("error") { if let Some(previous) = error.replace(variant) { errors.extend(vec![ Error::new("Only one #[error] variant can be declared.").span(span), Error::new("Previously declared #[error]:").span(previous.span()), ]); } } else if attr.path.is_ident("end") { errors.push( Error::new( "Since 0.11 Logos no longer requires the #[end] variant.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases" ).span(attr.span()) ); } else if attr.path.is_ident("token") { match util::value_from_attr("token", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let value = value.into_bytes(); let then = graph.push(token.priority(value.len())); ropes.push(Rope::new(value, then)); }, Err(err) => errors.push(err), _ => (), } } else if attr.path.is_ident("regex") { match util::value_from_attr("regex", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let then = graph.reserve(); let (utf8, regex, span) = match value { Literal::Utf8(string, span) => (true, string, span), Literal::Bytes(bytes, span) => { mode = Mode::Binary; (false, util::bytes_to_regex_string(&bytes), span) } }; match graph.regex(utf8, &regex, then.get()) { Ok((len, mut id)) => { let then = graph.insert(then, token.priority(len)); regex_ids.push(id); // Drain recursive miss values. // We need the root node to have straight branches. while let Some(miss) = graph[id].miss() { if miss == then { errors.push( Error::new("#[regex]: expression can match empty string.\n\n\ hint: consider changing * to +").span(span) ); break; } else { regex_ids.push(miss); id = miss; } } }, Err(err) => errors.push(err.span(span)), } }, Err(err) => errors.push(err), _ => (), } } } } let mut root = Fork::new(); let extras = match extras { Some(ext) => quote!(#ext), None => quote!(()), }; let source = match mode { Mode::Utf8 => quote!(str), Mode::Binary => quote!([u8]), }; let error_def = match error { Some(error) => Some(quote!(const ERROR: Self = #name::#error;)), None => { errors.push(Error::new("missing #[error] token variant.").span(super_span)); None }, }; let this = quote!(#name #generics); let impl_logos = |body| { quote! { impl<'s> ::logos::Logos<'s> for #this { type Extras = #extras; type Source = #source; const SIZE: usize = #size; #error_def fn lex(lex: &mut ::logos::Lexer<'s, Self>) { #body } } } }; if errors.len() > 0 { return impl_logos(quote! { fn _logos_derive_compile_errors() { #(#errors)* } }).into() } for id in regex_ids { let fork = graph.fork_off(id); root.merge(fork, &mut graph); } for rope in ropes { root.merge(rope.into_fork(&mut graph), &mut graph) } while let Some(id) = root.miss.take() { let fork = graph.fork_off(id); if fork.branches().next().is_some() { root.merge(fork, &mut graph); } else { break; } } let root = graph.push(root); graph.shake(root); // panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count()); let generator = Generator::new(name, &this, root, &graph); let body = generator.generate(); let tokens = impl_logos(quote! { use ::logos::internal::{LexerInternal, CallbackResult}; type Lexer<'s> = ::logos::Lexer<'s, #name #generics>; fn _end<'s>(lex: &mut Lexer<'s>) { lex.end() } fn _error<'s>(lex: &mut Lexer<'s>) { lex.bump_unchecked(1); lex.set(#name::#error); } #body }); // panic!("{}", tokens); TokenStream::from(tokens) }
identifier_body
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursion_limit = "196"] mod generator; mod error; mod graph; mod util; mod leaf; use error::Error; use generator::Generator; use graph::{Graph, Fork, Rope}; use leaf::Leaf; use util::{Literal, Definition}; use proc_macro::TokenStream; use quote::quote; use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute}; use syn::spanned::Spanned; enum Mode { Utf8, Binary, } #[proc_macro_derive( Logos, attributes(logos, extras, error, end, token, regex, extras) )] pub fn
(input: TokenStream) -> TokenStream { let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mode::Utf8; let mut errors = Vec::new(); let generics = match item.generics.params.len() { 0 => { None }, 1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => { Some(quote!(<'s>)) }, _ => { let span = item.generics.span(); errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span)); None } }; let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> { if attr.path.is_ident("logos") { if let Some(nested) = util::read_attr("logos", attr)? { let span = nested.span(); if let Some(ext) = util::value_from_nested("extras", &nested)? { if extras.replace(ext).is_some() { return Err(Error::new("Extras can be defined only once.").span(span)); } } if let Err(_) = util::value_from_nested("trivia", &nested) { const ERR: &str = "\ trivia are no longer supported.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(span)); } } } if attr.path.is_ident("extras") { const ERR: &str = "\ #[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(attr.span())); } Ok(()) }; for attr in &item.attrs { if let Err(err) = parse_attr(attr) { errors.push(err); } } let mut variants = Vec::new(); let mut ropes = Vec::new(); let mut regex_ids = Vec::new(); let mut graph = Graph::new(); for variant in &item.variants { variants.push(&variant.ident); let span = variant.span(); if let Some((_, value)) = &variant.discriminant { let span = value.span(); let value = util::unpack_int(value).unwrap_or(usize::max_value()); if value >= size { errors.push(Error::new( format!( "Discriminant value for `{}` is invalid. Expected integer in range 0..={}.", variant.ident, size, ), ).span(span)); } } let field = match &variant.fields { Fields::Unit => None, Fields::Unnamed(ref fields) => { if fields.unnamed.len() != 1 { errors.push(Error::new( format!( "Logos currently only supports variants with one field, found {}", fields.unnamed.len(), ) ).span(fields.span())) } let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone(); Some(field) } Fields::Named(_) => { errors.push(Error::new("Logos doesn't support named fields yet.").span(span)); None } }; for attr in &variant.attrs { let variant = &variant.ident; let mut with_definition = |definition: Definition<Literal>| { if let Literal::Bytes(..) = definition.value { mode = Mode::Binary; } ( Leaf::token(variant).field(field.clone()).callback(definition.callback), definition.value, ) }; if attr.path.is_ident("error") { if let Some(previous) = error.replace(variant) { errors.extend(vec![ Error::new("Only one #[error] variant can be declared.").span(span), Error::new("Previously declared #[error]:").span(previous.span()), ]); } } else if attr.path.is_ident("end") { errors.push( Error::new( "Since 0.11 Logos no longer requires the #[end] variant.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases" ).span(attr.span()) ); } else if attr.path.is_ident("token") { match util::value_from_attr("token", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let value = value.into_bytes(); let then = graph.push(token.priority(value.len())); ropes.push(Rope::new(value, then)); }, Err(err) => errors.push(err), _ => (), } } else if attr.path.is_ident("regex") { match util::value_from_attr("regex", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let then = graph.reserve(); let (utf8, regex, span) = match value { Literal::Utf8(string, span) => (true, string, span), Literal::Bytes(bytes, span) => { mode = Mode::Binary; (false, util::bytes_to_regex_string(&bytes), span) } }; match graph.regex(utf8, &regex, then.get()) { Ok((len, mut id)) => { let then = graph.insert(then, token.priority(len)); regex_ids.push(id); // Drain recursive miss values. // We need the root node to have straight branches. while let Some(miss) = graph[id].miss() { if miss == then { errors.push( Error::new("#[regex]: expression can match empty string.\n\n\ hint: consider changing * to +").span(span) ); break; } else { regex_ids.push(miss); id = miss; } } }, Err(err) => errors.push(err.span(span)), } }, Err(err) => errors.push(err), _ => (), } } } } let mut root = Fork::new(); let extras = match extras { Some(ext) => quote!(#ext), None => quote!(()), }; let source = match mode { Mode::Utf8 => quote!(str), Mode::Binary => quote!([u8]), }; let error_def = match error { Some(error) => Some(quote!(const ERROR: Self = #name::#error;)), None => { errors.push(Error::new("missing #[error] token variant.").span(super_span)); None }, }; let this = quote!(#name #generics); let impl_logos = |body| { quote! { impl<'s> ::logos::Logos<'s> for #this { type Extras = #extras; type Source = #source; const SIZE: usize = #size; #error_def fn lex(lex: &mut ::logos::Lexer<'s, Self>) { #body } } } }; if errors.len() > 0 { return impl_logos(quote! { fn _logos_derive_compile_errors() { #(#errors)* } }).into() } for id in regex_ids { let fork = graph.fork_off(id); root.merge(fork, &mut graph); } for rope in ropes { root.merge(rope.into_fork(&mut graph), &mut graph) } while let Some(id) = root.miss.take() { let fork = graph.fork_off(id); if fork.branches().next().is_some() { root.merge(fork, &mut graph); } else { break; } } let root = graph.push(root); graph.shake(root); // panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count()); let generator = Generator::new(name, &this, root, &graph); let body = generator.generate(); let tokens = impl_logos(quote! { use ::logos::internal::{LexerInternal, CallbackResult}; type Lexer<'s> = ::logos::Lexer<'s, #name #generics>; fn _end<'s>(lex: &mut Lexer<'s>) { lex.end() } fn _error<'s>(lex: &mut Lexer<'s>) { lex.bump_unchecked(1); lex.set(#name::#error); } #body }); // panic!("{}", tokens); TokenStream::from(tokens) }
logos
identifier_name
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursion_limit = "196"] mod generator; mod error; mod graph; mod util; mod leaf; use error::Error; use generator::Generator; use graph::{Graph, Fork, Rope}; use leaf::Leaf; use util::{Literal, Definition}; use proc_macro::TokenStream; use quote::quote; use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute}; use syn::spanned::Spanned; enum Mode { Utf8, Binary, } #[proc_macro_derive( Logos, attributes(logos, extras, error, end, token, regex, extras) )] pub fn logos(input: TokenStream) -> TokenStream { let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mode::Utf8; let mut errors = Vec::new(); let generics = match item.generics.params.len() { 0 => { None }, 1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => { Some(quote!(<'s>)) }, _ => { let span = item.generics.span(); errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span)); None } }; let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> { if attr.path.is_ident("logos") { if let Some(nested) = util::read_attr("logos", attr)? { let span = nested.span(); if let Some(ext) = util::value_from_nested("extras", &nested)? { if extras.replace(ext).is_some() { return Err(Error::new("Extras can be defined only once.").span(span)); } } if let Err(_) = util::value_from_nested("trivia", &nested) { const ERR: &str = "\ trivia are no longer supported.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(span)); } } } if attr.path.is_ident("extras") {
#[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(attr.span())); } Ok(()) }; for attr in &item.attrs { if let Err(err) = parse_attr(attr) { errors.push(err); } } let mut variants = Vec::new(); let mut ropes = Vec::new(); let mut regex_ids = Vec::new(); let mut graph = Graph::new(); for variant in &item.variants { variants.push(&variant.ident); let span = variant.span(); if let Some((_, value)) = &variant.discriminant { let span = value.span(); let value = util::unpack_int(value).unwrap_or(usize::max_value()); if value >= size { errors.push(Error::new( format!( "Discriminant value for `{}` is invalid. Expected integer in range 0..={}.", variant.ident, size, ), ).span(span)); } } let field = match &variant.fields { Fields::Unit => None, Fields::Unnamed(ref fields) => { if fields.unnamed.len() != 1 { errors.push(Error::new( format!( "Logos currently only supports variants with one field, found {}", fields.unnamed.len(), ) ).span(fields.span())) } let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone(); Some(field) } Fields::Named(_) => { errors.push(Error::new("Logos doesn't support named fields yet.").span(span)); None } }; for attr in &variant.attrs { let variant = &variant.ident; let mut with_definition = |definition: Definition<Literal>| { if let Literal::Bytes(..) = definition.value { mode = Mode::Binary; } ( Leaf::token(variant).field(field.clone()).callback(definition.callback), definition.value, ) }; if attr.path.is_ident("error") { if let Some(previous) = error.replace(variant) { errors.extend(vec![ Error::new("Only one #[error] variant can be declared.").span(span), Error::new("Previously declared #[error]:").span(previous.span()), ]); } } else if attr.path.is_ident("end") { errors.push( Error::new( "Since 0.11 Logos no longer requires the #[end] variant.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases" ).span(attr.span()) ); } else if attr.path.is_ident("token") { match util::value_from_attr("token", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let value = value.into_bytes(); let then = graph.push(token.priority(value.len())); ropes.push(Rope::new(value, then)); }, Err(err) => errors.push(err), _ => (), } } else if attr.path.is_ident("regex") { match util::value_from_attr("regex", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let then = graph.reserve(); let (utf8, regex, span) = match value { Literal::Utf8(string, span) => (true, string, span), Literal::Bytes(bytes, span) => { mode = Mode::Binary; (false, util::bytes_to_regex_string(&bytes), span) } }; match graph.regex(utf8, &regex, then.get()) { Ok((len, mut id)) => { let then = graph.insert(then, token.priority(len)); regex_ids.push(id); // Drain recursive miss values. // We need the root node to have straight branches. while let Some(miss) = graph[id].miss() { if miss == then { errors.push( Error::new("#[regex]: expression can match empty string.\n\n\ hint: consider changing * to +").span(span) ); break; } else { regex_ids.push(miss); id = miss; } } }, Err(err) => errors.push(err.span(span)), } }, Err(err) => errors.push(err), _ => (), } } } } let mut root = Fork::new(); let extras = match extras { Some(ext) => quote!(#ext), None => quote!(()), }; let source = match mode { Mode::Utf8 => quote!(str), Mode::Binary => quote!([u8]), }; let error_def = match error { Some(error) => Some(quote!(const ERROR: Self = #name::#error;)), None => { errors.push(Error::new("missing #[error] token variant.").span(super_span)); None }, }; let this = quote!(#name #generics); let impl_logos = |body| { quote! { impl<'s> ::logos::Logos<'s> for #this { type Extras = #extras; type Source = #source; const SIZE: usize = #size; #error_def fn lex(lex: &mut ::logos::Lexer<'s, Self>) { #body } } } }; if errors.len() > 0 { return impl_logos(quote! { fn _logos_derive_compile_errors() { #(#errors)* } }).into() } for id in regex_ids { let fork = graph.fork_off(id); root.merge(fork, &mut graph); } for rope in ropes { root.merge(rope.into_fork(&mut graph), &mut graph) } while let Some(id) = root.miss.take() { let fork = graph.fork_off(id); if fork.branches().next().is_some() { root.merge(fork, &mut graph); } else { break; } } let root = graph.push(root); graph.shake(root); // panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count()); let generator = Generator::new(name, &this, root, &graph); let body = generator.generate(); let tokens = impl_logos(quote! { use ::logos::internal::{LexerInternal, CallbackResult}; type Lexer<'s> = ::logos::Lexer<'s, #name #generics>; fn _end<'s>(lex: &mut Lexer<'s>) { lex.end() } fn _error<'s>(lex: &mut Lexer<'s>) { lex.bump_unchecked(1); lex.set(#name::#error); } #body }); // panic!("{}", tokens); TokenStream::from(tokens) }
const ERR: &str = "\
random_line_split
lib.rs
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right"> //! //! # Logos //! //! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos). // The `quote!` macro requires deep recursion. #![recursion_limit = "196"] mod generator; mod error; mod graph; mod util; mod leaf; use error::Error; use generator::Generator; use graph::{Graph, Fork, Rope}; use leaf::Leaf; use util::{Literal, Definition}; use proc_macro::TokenStream; use quote::quote; use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute}; use syn::spanned::Spanned; enum Mode { Utf8, Binary, } #[proc_macro_derive( Logos, attributes(logos, extras, error, end, token, regex, extras) )] pub fn logos(input: TokenStream) -> TokenStream { let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums"); let super_span = item.span(); let size = item.variants.len(); let name = &item.ident; let mut extras: Option<Ident> = None; let mut error = None; let mut mode = Mode::Utf8; let mut errors = Vec::new(); let generics = match item.generics.params.len() { 0 => { None }, 1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => { Some(quote!(<'s>)) }, _ => { let span = item.generics.span(); errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span)); None } }; let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> { if attr.path.is_ident("logos") { if let Some(nested) = util::read_attr("logos", attr)? { let span = nested.span(); if let Some(ext) = util::value_from_nested("extras", &nested)? { if extras.replace(ext).is_some() { return Err(Error::new("Extras can be defined only once.").span(span)); } } if let Err(_) = util::value_from_nested("trivia", &nested) { const ERR: &str = "\ trivia are no longer supported.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(span)); } } } if attr.path.is_ident("extras") { const ERR: &str = "\ #[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"; return Err(Error::new(ERR).span(attr.span())); } Ok(()) }; for attr in &item.attrs { if let Err(err) = parse_attr(attr) { errors.push(err); } } let mut variants = Vec::new(); let mut ropes = Vec::new(); let mut regex_ids = Vec::new(); let mut graph = Graph::new(); for variant in &item.variants { variants.push(&variant.ident); let span = variant.span(); if let Some((_, value)) = &variant.discriminant { let span = value.span(); let value = util::unpack_int(value).unwrap_or(usize::max_value()); if value >= size { errors.push(Error::new( format!( "Discriminant value for `{}` is invalid. Expected integer in range 0..={}.", variant.ident, size, ), ).span(span)); } } let field = match &variant.fields { Fields::Unit => None, Fields::Unnamed(ref fields) => { if fields.unnamed.len() != 1 { errors.push(Error::new( format!( "Logos currently only supports variants with one field, found {}", fields.unnamed.len(), ) ).span(fields.span())) } let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone(); Some(field) } Fields::Named(_) => { errors.push(Error::new("Logos doesn't support named fields yet.").span(span)); None } }; for attr in &variant.attrs { let variant = &variant.ident; let mut with_definition = |definition: Definition<Literal>| { if let Literal::Bytes(..) = definition.value { mode = Mode::Binary; } ( Leaf::token(variant).field(field.clone()).callback(definition.callback), definition.value, ) }; if attr.path.is_ident("error") { if let Some(previous) = error.replace(variant) { errors.extend(vec![ Error::new("Only one #[error] variant can be declared.").span(span), Error::new("Previously declared #[error]:").span(previous.span()), ]); } } else if attr.path.is_ident("end") { errors.push( Error::new( "Since 0.11 Logos no longer requires the #[end] variant.\n\n\ For help with migration see release notes: https://github.com/maciejhirsz/logos/releases" ).span(attr.span()) ); } else if attr.path.is_ident("token") { match util::value_from_attr("token", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let value = value.into_bytes(); let then = graph.push(token.priority(value.len())); ropes.push(Rope::new(value, then)); }, Err(err) => errors.push(err), _ => (), } } else if attr.path.is_ident("regex") { match util::value_from_attr("regex", attr) { Ok(Some(definition)) => { let (token, value) = with_definition(definition); let then = graph.reserve(); let (utf8, regex, span) = match value { Literal::Utf8(string, span) => (true, string, span), Literal::Bytes(bytes, span) => { mode = Mode::Binary; (false, util::bytes_to_regex_string(&bytes), span) } }; match graph.regex(utf8, &regex, then.get()) { Ok((len, mut id)) => { let then = graph.insert(then, token.priority(len)); regex_ids.push(id); // Drain recursive miss values. // We need the root node to have straight branches. while let Some(miss) = graph[id].miss() { if miss == then { errors.push( Error::new("#[regex]: expression can match empty string.\n\n\ hint: consider changing * to +").span(span) ); break; } else { regex_ids.push(miss); id = miss; } } }, Err(err) => errors.push(err.span(span)), } }, Err(err) => errors.push(err), _ => (), } } } } let mut root = Fork::new(); let extras = match extras { Some(ext) => quote!(#ext), None => quote!(()), }; let source = match mode { Mode::Utf8 => quote!(str), Mode::Binary => quote!([u8]), }; let error_def = match error { Some(error) => Some(quote!(const ERROR: Self = #name::#error;)), None => { errors.push(Error::new("missing #[error] token variant.").span(super_span)); None }, }; let this = quote!(#name #generics); let impl_logos = |body| { quote! { impl<'s> ::logos::Logos<'s> for #this { type Extras = #extras; type Source = #source; const SIZE: usize = #size; #error_def fn lex(lex: &mut ::logos::Lexer<'s, Self>) { #body } } } }; if errors.len() > 0 { return impl_logos(quote! { fn _logos_derive_compile_errors() { #(#errors)* } }).into() } for id in regex_ids { let fork = graph.fork_off(id); root.merge(fork, &mut graph); } for rope in ropes { root.merge(rope.into_fork(&mut graph), &mut graph) } while let Some(id) = root.miss.take() { let fork = graph.fork_off(id); if fork.branches().next().is_some() { root.merge(fork, &mut graph); } else
} let root = graph.push(root); graph.shake(root); // panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count()); let generator = Generator::new(name, &this, root, &graph); let body = generator.generate(); let tokens = impl_logos(quote! { use ::logos::internal::{LexerInternal, CallbackResult}; type Lexer<'s> = ::logos::Lexer<'s, #name #generics>; fn _end<'s>(lex: &mut Lexer<'s>) { lex.end() } fn _error<'s>(lex: &mut Lexer<'s>) { lex.bump_unchecked(1); lex.set(#name::#error); } #body }); // panic!("{}", tokens); TokenStream::from(tokens) }
{ break; }
conditional_block
login.go
package commands import ( "errors" "strconv" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/command" "code.cloudfoundry.org/cli/command/translatableerror" "code.cloudfoundry.org/cli/cf/api/authentication" "code.cloudfoundry.org/cli/cf/api/organizations" "code.cloudfoundry.org/cli/cf/api/spaces" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/models" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) const maxLoginTries = 3 const maxChoices = 50 type Login struct { ui terminal.UI config coreconfig.ReadWriter authenticator authentication.Repository endpointRepo coreconfig.EndpointRepository orgRepo organizations.OrganizationRepository spaceRepo spaces.SpaceRepository } func init() { commandregistry.Register(&Login{}) } func (cmd *Login) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["a"] = &flags.StringFlag{ShortName: "a", Usage: T("API endpoint (e.g. https://api.example.com)")} fs["u"] = &flags.StringFlag{ShortName: "u", Usage: T("Username")} fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Password")} fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")} fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")} fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")} fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("One-time passcode")} fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")} return commandregistry.CommandMetadata{ Name: "login", ShortName: "l", Description: T("Log user in"), Usage: []string{ T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"), terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")), }, Examples: []string{ T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"), T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"), T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"), T("CF_NAME login -u name@example.com -p \"\\\"password\\\"\" (escape quotes if used in password)"), T("CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)"), }, Flags: fs, } } func (cmd *Login) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { reqs := []requirements.Requirement{} return reqs, nil } func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository() cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository() cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository() cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository() return cmd } func (cmd *Login) Execute(c flags.FlagContext) error { cmd.config.ClearSession() endpoint, skipSSL := cmd.decideEndpoint(c) api := API{ ui: cmd.ui, config: cmd.config, endpointRepo: cmd.endpointRepo, } err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name) if err != nil { return err } err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion) if err != nil { if _, ok := err.(translatableerror.MinimumCFAPIVersionNotMetError); ok { cmd.ui.Warn("Your API version is no longer supported. Upgrade to a newer version of the API.") } else { return err } } defer func() { cmd.ui.Say("") cmd.ui.ShowConfiguration(cmd.config) }() // We thought we would never need to explicitly branch in this code // for anything as simple as authentication, but it turns out that our // assumptions did not match reality. // When SAML is enabled (but not configured) then the UAA/Login server // will always returns password prompts that includes the Passcode field. // Users can authenticate with: // EITHER username and password // OR a one-time passcode switch { case c.Bool("sso") && c.IsSet("sso-passcode"): return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso")) case c.Bool("sso") || c.IsSet("sso-passcode"): err = cmd.authenticateSSO(c) if err != nil { return err } default: err = cmd.authenticate(c) if err != nil { return err } } orgIsSet, err := cmd.setOrganization(c) if err != nil { return err } if orgIsSet { err = cmd.setSpace(c) if err != nil { return err } } cmd.ui.NotifyUpdateIfNeeded(cmd.config) return nil } func (cmd Login) decideEndpoint(c flags.FlagContext) (string, bool) { endpoint := c.String("a") skipSSL := c.Bool("skip-ssl-validation") if endpoint == "" { endpoint = cmd.config.APIEndpoint() skipSSL = cmd.config.IsSSLDisabled() || skipSSL } if endpoint == "" { endpoint = cmd.ui.Ask(T("API endpoint")) } else { cmd.ui.Say(T("API endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)})) } return endpoint, skipSSL } func (cmd Login) authenticateSSO(c flags.FlagContext) error { prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } credentials := make(map[string]string) passcode := prompts["passcode"] if passcode.DisplayName == "" { passcode = coreconfig.AuthPrompt{ Type: coreconfig.AuthPromptTypePassword, DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )", map[string]interface{}{ "AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(), }), } } for i := 0; i < maxLoginTries; i++ { if c.IsSet("sso-passcode") && i == 0 { credentials["passcode"] = c.String("sso-passcode") } else { credentials["passcode"] = cmd.ui.AskForPassword(passcode.DisplayName) } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentials) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) authenticate(c flags.FlagContext) error { if cmd.config.UAAGrantType() == "client_credentials" { return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again.")) } usernameFlagValue := c.String("u") passwordFlagValue := c.String("p") prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } passwordKeys := []string{} credentials := make(map[string]string) if value, ok := prompts["username"]; ok { if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" { credentials["username"] = usernameFlagValue } else { credentials["username"] = cmd.ui.Ask(T(value.DisplayName)) } } for key, prompt := range prompts { if prompt.Type == coreconfig.AuthPromptTypePassword { if key == "passcode" || key == "password" { continue } passwordKeys = append(passwordKeys, key) } else if key == "username" { continue } else { credentials[key] = cmd.ui.Ask(T(prompt.DisplayName)) } } for i := 0; i < maxLoginTries; i++ { // ensure that password gets prompted before other codes (eg. mfa code) if passPrompt, ok := prompts["password"]; ok { if passwordFlagValue != "" { credentials["password"] = passwordFlagValue passwordFlagValue = "" } else { credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName)) } } for _, key := range passwordKeys { credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName)) } credentialsCopy := make(map[string]string, len(credentials)) for k, v := range credentials { credentialsCopy[k] = v } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentialsCopy) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) { orgName := c.String("o") if orgName == "" { orgs, err := cmd.orgRepo.ListOrgs(maxChoices) if err != nil { return false, errors.New(T("Error finding available orgs\n{{.APIErr}}", map[string]interface{}{"APIErr": err.Error()})) } switch len(orgs) { case 0: return false, nil case 1: cmd.targetOrganization(orgs[0]) return true, nil default: orgName = cmd.promptForOrgName(orgs) if orgName == "" { cmd.ui.Say("") return false, nil } } } org, err := cmd.orgRepo.FindByName(orgName) if err != nil { return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}", map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()})) } cmd.targetOrganization(org) return true, nil } func (cmd Login) promptForOrgName(orgs []models.Organization) string { orgNames := []string{} for _, org := range orgs { orgNames = append(orgNames, org.Name) } return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org") } func (cmd Login) targetOrganization(org models.Organization) { cmd.config.SetOrganizationFields(org.OrganizationFields) cmd.ui.Say(T("Targeted org {{.OrgName}}\n", map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)})) } func (cmd Login) setSpace(c flags.FlagContext) error { spaceName := c.String("s") if spaceName == "" { var availableSpaces []models.Space err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool { availableSpaces = append(availableSpaces, space) return (len(availableSpaces) < maxChoices) }) if err != nil { return errors.New(T("Error finding available spaces\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } if len(availableSpaces) == 0 { return nil } else if len(availableSpaces) == 1 { cmd.targetSpace(availableSpaces[0]) return nil } else { spaceName = cmd.promptForSpaceName(availableSpaces) if spaceName == "" { cmd.ui.Say("") return nil } } } space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { return errors.New(T("Error finding space {{.SpaceName}}\n{{.Err}}", map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()})) } cmd.targetSpace(space) return nil } func (cmd Login) promptForSpaceName(spaces []models.Space) string { spaceNames := []string{} for _, space := range spaces { spaceNames = append(spaceNames, space.Name) } return cmd.promptForName(spaceNames, T("Select a space (or press enter to skip):"), "Space") } func (cmd Login) targetSpace(space models.Space)
func (cmd Login) promptForName(names []string, listPrompt, itemPrompt string) string { nameIndex := 0 var nameString string for nameIndex < 1 || nameIndex > len(names) { var err error // list header cmd.ui.Say(listPrompt) // only display list if it is shorter than maxChoices if len(names) < maxChoices { for i, name := range names { cmd.ui.Say("%d. %s", i+1, name) } } else { cmd.ui.Say(T("There are too many options to display, please type in the name.")) } nameString = cmd.ui.Ask(itemPrompt) if nameString == "" { return "" } nameIndex, err = strconv.Atoi(nameString) if err != nil { nameIndex = 1 return nameString } } return names[nameIndex-1] }
{ cmd.config.SetSpaceFields(space.SpaceFields) cmd.ui.Say(T("Targeted space {{.SpaceName}}\n", map[string]interface{}{"SpaceName": terminal.EntityNameColor(space.Name)})) }
identifier_body
login.go
package commands import ( "errors" "strconv" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/command" "code.cloudfoundry.org/cli/command/translatableerror" "code.cloudfoundry.org/cli/cf/api/authentication" "code.cloudfoundry.org/cli/cf/api/organizations" "code.cloudfoundry.org/cli/cf/api/spaces" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/models" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) const maxLoginTries = 3 const maxChoices = 50 type Login struct { ui terminal.UI config coreconfig.ReadWriter authenticator authentication.Repository endpointRepo coreconfig.EndpointRepository orgRepo organizations.OrganizationRepository spaceRepo spaces.SpaceRepository } func init() { commandregistry.Register(&Login{}) } func (cmd *Login) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["a"] = &flags.StringFlag{ShortName: "a", Usage: T("API endpoint (e.g. https://api.example.com)")} fs["u"] = &flags.StringFlag{ShortName: "u", Usage: T("Username")} fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Password")} fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")} fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")} fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")} fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("One-time passcode")} fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")} return commandregistry.CommandMetadata{ Name: "login", ShortName: "l", Description: T("Log user in"), Usage: []string{ T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"), terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")), }, Examples: []string{ T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"), T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"), T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"), T("CF_NAME login -u name@example.com -p \"\\\"password\\\"\" (escape quotes if used in password)"), T("CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)"), }, Flags: fs, } } func (cmd *Login) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { reqs := []requirements.Requirement{} return reqs, nil } func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository() cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository() cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository() cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository() return cmd } func (cmd *Login) Execute(c flags.FlagContext) error { cmd.config.ClearSession() endpoint, skipSSL := cmd.decideEndpoint(c) api := API{ ui: cmd.ui, config: cmd.config, endpointRepo: cmd.endpointRepo, } err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name) if err != nil { return err } err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion) if err != nil { if _, ok := err.(translatableerror.MinimumCFAPIVersionNotMetError); ok { cmd.ui.Warn("Your API version is no longer supported. Upgrade to a newer version of the API.") } else { return err } } defer func() { cmd.ui.Say("") cmd.ui.ShowConfiguration(cmd.config) }() // We thought we would never need to explicitly branch in this code // for anything as simple as authentication, but it turns out that our // assumptions did not match reality. // When SAML is enabled (but not configured) then the UAA/Login server // will always returns password prompts that includes the Passcode field. // Users can authenticate with: // EITHER username and password // OR a one-time passcode switch { case c.Bool("sso") && c.IsSet("sso-passcode"): return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso")) case c.Bool("sso") || c.IsSet("sso-passcode"): err = cmd.authenticateSSO(c) if err != nil { return err } default: err = cmd.authenticate(c) if err != nil { return err } } orgIsSet, err := cmd.setOrganization(c) if err != nil { return err } if orgIsSet { err = cmd.setSpace(c) if err != nil { return err } } cmd.ui.NotifyUpdateIfNeeded(cmd.config) return nil } func (cmd Login) decideEndpoint(c flags.FlagContext) (string, bool) { endpoint := c.String("a") skipSSL := c.Bool("skip-ssl-validation") if endpoint == "" { endpoint = cmd.config.APIEndpoint() skipSSL = cmd.config.IsSSLDisabled() || skipSSL } if endpoint == "" { endpoint = cmd.ui.Ask(T("API endpoint")) } else { cmd.ui.Say(T("API endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)})) } return endpoint, skipSSL } func (cmd Login) authenticateSSO(c flags.FlagContext) error { prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } credentials := make(map[string]string) passcode := prompts["passcode"] if passcode.DisplayName == "" { passcode = coreconfig.AuthPrompt{ Type: coreconfig.AuthPromptTypePassword, DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )", map[string]interface{}{ "AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(), }), } } for i := 0; i < maxLoginTries; i++ { if c.IsSet("sso-passcode") && i == 0 { credentials["passcode"] = c.String("sso-passcode") } else { credentials["passcode"] = cmd.ui.AskForPassword(passcode.DisplayName) } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentials) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) authenticate(c flags.FlagContext) error { if cmd.config.UAAGrantType() == "client_credentials" { return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again.")) } usernameFlagValue := c.String("u") passwordFlagValue := c.String("p") prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } passwordKeys := []string{} credentials := make(map[string]string) if value, ok := prompts["username"]; ok { if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" { credentials["username"] = usernameFlagValue } else { credentials["username"] = cmd.ui.Ask(T(value.DisplayName)) } } for key, prompt := range prompts { if prompt.Type == coreconfig.AuthPromptTypePassword { if key == "passcode" || key == "password" { continue } passwordKeys = append(passwordKeys, key) } else if key == "username" { continue } else { credentials[key] = cmd.ui.Ask(T(prompt.DisplayName)) } } for i := 0; i < maxLoginTries; i++ { // ensure that password gets prompted before other codes (eg. mfa code) if passPrompt, ok := prompts["password"]; ok { if passwordFlagValue != "" { credentials["password"] = passwordFlagValue passwordFlagValue = "" } else { credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName)) } } for _, key := range passwordKeys { credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName)) } credentialsCopy := make(map[string]string, len(credentials)) for k, v := range credentials { credentialsCopy[k] = v } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentialsCopy) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) { orgName := c.String("o") if orgName == "" { orgs, err := cmd.orgRepo.ListOrgs(maxChoices) if err != nil { return false, errors.New(T("Error finding available orgs\n{{.APIErr}}", map[string]interface{}{"APIErr": err.Error()})) } switch len(orgs) { case 0: return false, nil case 1: cmd.targetOrganization(orgs[0]) return true, nil default: orgName = cmd.promptForOrgName(orgs) if orgName == "" { cmd.ui.Say("") return false, nil } } } org, err := cmd.orgRepo.FindByName(orgName) if err != nil { return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}", map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()})) } cmd.targetOrganization(org) return true, nil } func (cmd Login) promptForOrgName(orgs []models.Organization) string { orgNames := []string{} for _, org := range orgs { orgNames = append(orgNames, org.Name) } return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org") } func (cmd Login) targetOrganization(org models.Organization) { cmd.config.SetOrganizationFields(org.OrganizationFields) cmd.ui.Say(T("Targeted org {{.OrgName}}\n", map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)})) } func (cmd Login) setSpace(c flags.FlagContext) error { spaceName := c.String("s") if spaceName == "" { var availableSpaces []models.Space err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool { availableSpaces = append(availableSpaces, space) return (len(availableSpaces) < maxChoices) })
map[string]interface{}{"Err": err.Error()})) } if len(availableSpaces) == 0 { return nil } else if len(availableSpaces) == 1 { cmd.targetSpace(availableSpaces[0]) return nil } else { spaceName = cmd.promptForSpaceName(availableSpaces) if spaceName == "" { cmd.ui.Say("") return nil } } } space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { return errors.New(T("Error finding space {{.SpaceName}}\n{{.Err}}", map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()})) } cmd.targetSpace(space) return nil } func (cmd Login) promptForSpaceName(spaces []models.Space) string { spaceNames := []string{} for _, space := range spaces { spaceNames = append(spaceNames, space.Name) } return cmd.promptForName(spaceNames, T("Select a space (or press enter to skip):"), "Space") } func (cmd Login) targetSpace(space models.Space) { cmd.config.SetSpaceFields(space.SpaceFields) cmd.ui.Say(T("Targeted space {{.SpaceName}}\n", map[string]interface{}{"SpaceName": terminal.EntityNameColor(space.Name)})) } func (cmd Login) promptForName(names []string, listPrompt, itemPrompt string) string { nameIndex := 0 var nameString string for nameIndex < 1 || nameIndex > len(names) { var err error // list header cmd.ui.Say(listPrompt) // only display list if it is shorter than maxChoices if len(names) < maxChoices { for i, name := range names { cmd.ui.Say("%d. %s", i+1, name) } } else { cmd.ui.Say(T("There are too many options to display, please type in the name.")) } nameString = cmd.ui.Ask(itemPrompt) if nameString == "" { return "" } nameIndex, err = strconv.Atoi(nameString) if err != nil { nameIndex = 1 return nameString } } return names[nameIndex-1] }
if err != nil { return errors.New(T("Error finding available spaces\n{{.Err}}",
random_line_split
login.go
package commands import ( "errors" "strconv" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/command" "code.cloudfoundry.org/cli/command/translatableerror" "code.cloudfoundry.org/cli/cf/api/authentication" "code.cloudfoundry.org/cli/cf/api/organizations" "code.cloudfoundry.org/cli/cf/api/spaces" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/models" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) const maxLoginTries = 3 const maxChoices = 50 type Login struct { ui terminal.UI config coreconfig.ReadWriter authenticator authentication.Repository endpointRepo coreconfig.EndpointRepository orgRepo organizations.OrganizationRepository spaceRepo spaces.SpaceRepository } func init() { commandregistry.Register(&Login{}) } func (cmd *Login) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["a"] = &flags.StringFlag{ShortName: "a", Usage: T("API endpoint (e.g. https://api.example.com)")} fs["u"] = &flags.StringFlag{ShortName: "u", Usage: T("Username")} fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Password")} fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")} fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")} fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")} fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("One-time passcode")} fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")} return commandregistry.CommandMetadata{ Name: "login", ShortName: "l", Description: T("Log user in"), Usage: []string{ T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"), terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")), }, Examples: []string{ T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"), T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"), T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"), T("CF_NAME login -u name@example.com -p \"\\\"password\\\"\" (escape quotes if used in password)"), T("CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)"), }, Flags: fs, } } func (cmd *Login) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { reqs := []requirements.Requirement{} return reqs, nil } func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository() cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository() cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository() cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository() return cmd } func (cmd *Login) Execute(c flags.FlagContext) error { cmd.config.ClearSession() endpoint, skipSSL := cmd.decideEndpoint(c) api := API{ ui: cmd.ui, config: cmd.config, endpointRepo: cmd.endpointRepo, } err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name) if err != nil { return err } err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion) if err != nil { if _, ok := err.(translatableerror.MinimumCFAPIVersionNotMetError); ok { cmd.ui.Warn("Your API version is no longer supported. Upgrade to a newer version of the API.") } else { return err } } defer func() { cmd.ui.Say("") cmd.ui.ShowConfiguration(cmd.config) }() // We thought we would never need to explicitly branch in this code // for anything as simple as authentication, but it turns out that our // assumptions did not match reality. // When SAML is enabled (but not configured) then the UAA/Login server // will always returns password prompts that includes the Passcode field. // Users can authenticate with: // EITHER username and password // OR a one-time passcode switch { case c.Bool("sso") && c.IsSet("sso-passcode"): return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso")) case c.Bool("sso") || c.IsSet("sso-passcode"): err = cmd.authenticateSSO(c) if err != nil { return err } default: err = cmd.authenticate(c) if err != nil { return err } } orgIsSet, err := cmd.setOrganization(c) if err != nil { return err } if orgIsSet { err = cmd.setSpace(c) if err != nil { return err } } cmd.ui.NotifyUpdateIfNeeded(cmd.config) return nil } func (cmd Login)
(c flags.FlagContext) (string, bool) { endpoint := c.String("a") skipSSL := c.Bool("skip-ssl-validation") if endpoint == "" { endpoint = cmd.config.APIEndpoint() skipSSL = cmd.config.IsSSLDisabled() || skipSSL } if endpoint == "" { endpoint = cmd.ui.Ask(T("API endpoint")) } else { cmd.ui.Say(T("API endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)})) } return endpoint, skipSSL } func (cmd Login) authenticateSSO(c flags.FlagContext) error { prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } credentials := make(map[string]string) passcode := prompts["passcode"] if passcode.DisplayName == "" { passcode = coreconfig.AuthPrompt{ Type: coreconfig.AuthPromptTypePassword, DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )", map[string]interface{}{ "AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(), }), } } for i := 0; i < maxLoginTries; i++ { if c.IsSet("sso-passcode") && i == 0 { credentials["passcode"] = c.String("sso-passcode") } else { credentials["passcode"] = cmd.ui.AskForPassword(passcode.DisplayName) } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentials) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) authenticate(c flags.FlagContext) error { if cmd.config.UAAGrantType() == "client_credentials" { return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again.")) } usernameFlagValue := c.String("u") passwordFlagValue := c.String("p") prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } passwordKeys := []string{} credentials := make(map[string]string) if value, ok := prompts["username"]; ok { if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" { credentials["username"] = usernameFlagValue } else { credentials["username"] = cmd.ui.Ask(T(value.DisplayName)) } } for key, prompt := range prompts { if prompt.Type == coreconfig.AuthPromptTypePassword { if key == "passcode" || key == "password" { continue } passwordKeys = append(passwordKeys, key) } else if key == "username" { continue } else { credentials[key] = cmd.ui.Ask(T(prompt.DisplayName)) } } for i := 0; i < maxLoginTries; i++ { // ensure that password gets prompted before other codes (eg. mfa code) if passPrompt, ok := prompts["password"]; ok { if passwordFlagValue != "" { credentials["password"] = passwordFlagValue passwordFlagValue = "" } else { credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName)) } } for _, key := range passwordKeys { credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName)) } credentialsCopy := make(map[string]string, len(credentials)) for k, v := range credentials { credentialsCopy[k] = v } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentialsCopy) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) { orgName := c.String("o") if orgName == "" { orgs, err := cmd.orgRepo.ListOrgs(maxChoices) if err != nil { return false, errors.New(T("Error finding available orgs\n{{.APIErr}}", map[string]interface{}{"APIErr": err.Error()})) } switch len(orgs) { case 0: return false, nil case 1: cmd.targetOrganization(orgs[0]) return true, nil default: orgName = cmd.promptForOrgName(orgs) if orgName == "" { cmd.ui.Say("") return false, nil } } } org, err := cmd.orgRepo.FindByName(orgName) if err != nil { return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}", map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()})) } cmd.targetOrganization(org) return true, nil } func (cmd Login) promptForOrgName(orgs []models.Organization) string { orgNames := []string{} for _, org := range orgs { orgNames = append(orgNames, org.Name) } return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org") } func (cmd Login) targetOrganization(org models.Organization) { cmd.config.SetOrganizationFields(org.OrganizationFields) cmd.ui.Say(T("Targeted org {{.OrgName}}\n", map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)})) } func (cmd Login) setSpace(c flags.FlagContext) error { spaceName := c.String("s") if spaceName == "" { var availableSpaces []models.Space err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool { availableSpaces = append(availableSpaces, space) return (len(availableSpaces) < maxChoices) }) if err != nil { return errors.New(T("Error finding available spaces\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } if len(availableSpaces) == 0 { return nil } else if len(availableSpaces) == 1 { cmd.targetSpace(availableSpaces[0]) return nil } else { spaceName = cmd.promptForSpaceName(availableSpaces) if spaceName == "" { cmd.ui.Say("") return nil } } } space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { return errors.New(T("Error finding space {{.SpaceName}}\n{{.Err}}", map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()})) } cmd.targetSpace(space) return nil } func (cmd Login) promptForSpaceName(spaces []models.Space) string { spaceNames := []string{} for _, space := range spaces { spaceNames = append(spaceNames, space.Name) } return cmd.promptForName(spaceNames, T("Select a space (or press enter to skip):"), "Space") } func (cmd Login) targetSpace(space models.Space) { cmd.config.SetSpaceFields(space.SpaceFields) cmd.ui.Say(T("Targeted space {{.SpaceName}}\n", map[string]interface{}{"SpaceName": terminal.EntityNameColor(space.Name)})) } func (cmd Login) promptForName(names []string, listPrompt, itemPrompt string) string { nameIndex := 0 var nameString string for nameIndex < 1 || nameIndex > len(names) { var err error // list header cmd.ui.Say(listPrompt) // only display list if it is shorter than maxChoices if len(names) < maxChoices { for i, name := range names { cmd.ui.Say("%d. %s", i+1, name) } } else { cmd.ui.Say(T("There are too many options to display, please type in the name.")) } nameString = cmd.ui.Ask(itemPrompt) if nameString == "" { return "" } nameIndex, err = strconv.Atoi(nameString) if err != nil { nameIndex = 1 return nameString } } return names[nameIndex-1] }
decideEndpoint
identifier_name
login.go
package commands import ( "errors" "strconv" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/cf/commandregistry" "code.cloudfoundry.org/cli/cf/flags" . "code.cloudfoundry.org/cli/cf/i18n" "code.cloudfoundry.org/cli/command" "code.cloudfoundry.org/cli/command/translatableerror" "code.cloudfoundry.org/cli/cf/api/authentication" "code.cloudfoundry.org/cli/cf/api/organizations" "code.cloudfoundry.org/cli/cf/api/spaces" "code.cloudfoundry.org/cli/cf/configuration/coreconfig" "code.cloudfoundry.org/cli/cf/models" "code.cloudfoundry.org/cli/cf/requirements" "code.cloudfoundry.org/cli/cf/terminal" ) const maxLoginTries = 3 const maxChoices = 50 type Login struct { ui terminal.UI config coreconfig.ReadWriter authenticator authentication.Repository endpointRepo coreconfig.EndpointRepository orgRepo organizations.OrganizationRepository spaceRepo spaces.SpaceRepository } func init() { commandregistry.Register(&Login{}) } func (cmd *Login) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["a"] = &flags.StringFlag{ShortName: "a", Usage: T("API endpoint (e.g. https://api.example.com)")} fs["u"] = &flags.StringFlag{ShortName: "u", Usage: T("Username")} fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Password")} fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")} fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")} fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")} fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("One-time passcode")} fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")} return commandregistry.CommandMetadata{ Name: "login", ShortName: "l", Description: T("Log user in"), Usage: []string{ T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"), terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")), }, Examples: []string{ T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"), T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"), T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"), T("CF_NAME login -u name@example.com -p \"\\\"password\\\"\" (escape quotes if used in password)"), T("CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)"), }, Flags: fs, } } func (cmd *Login) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { reqs := []requirements.Requirement{} return reqs, nil } func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository() cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository() cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository() cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository() return cmd } func (cmd *Login) Execute(c flags.FlagContext) error { cmd.config.ClearSession() endpoint, skipSSL := cmd.decideEndpoint(c) api := API{ ui: cmd.ui, config: cmd.config, endpointRepo: cmd.endpointRepo, } err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name) if err != nil { return err } err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion) if err != nil { if _, ok := err.(translatableerror.MinimumCFAPIVersionNotMetError); ok { cmd.ui.Warn("Your API version is no longer supported. Upgrade to a newer version of the API.") } else { return err } } defer func() { cmd.ui.Say("") cmd.ui.ShowConfiguration(cmd.config) }() // We thought we would never need to explicitly branch in this code // for anything as simple as authentication, but it turns out that our // assumptions did not match reality. // When SAML is enabled (but not configured) then the UAA/Login server // will always returns password prompts that includes the Passcode field. // Users can authenticate with: // EITHER username and password // OR a one-time passcode switch { case c.Bool("sso") && c.IsSet("sso-passcode"): return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso")) case c.Bool("sso") || c.IsSet("sso-passcode"): err = cmd.authenticateSSO(c) if err != nil { return err } default: err = cmd.authenticate(c) if err != nil { return err } } orgIsSet, err := cmd.setOrganization(c) if err != nil { return err } if orgIsSet { err = cmd.setSpace(c) if err != nil { return err } } cmd.ui.NotifyUpdateIfNeeded(cmd.config) return nil } func (cmd Login) decideEndpoint(c flags.FlagContext) (string, bool) { endpoint := c.String("a") skipSSL := c.Bool("skip-ssl-validation") if endpoint == "" { endpoint = cmd.config.APIEndpoint() skipSSL = cmd.config.IsSSLDisabled() || skipSSL } if endpoint == "" { endpoint = cmd.ui.Ask(T("API endpoint")) } else { cmd.ui.Say(T("API endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)})) } return endpoint, skipSSL } func (cmd Login) authenticateSSO(c flags.FlagContext) error { prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } credentials := make(map[string]string) passcode := prompts["passcode"] if passcode.DisplayName == "" { passcode = coreconfig.AuthPrompt{ Type: coreconfig.AuthPromptTypePassword, DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )", map[string]interface{}{ "AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(), }), } } for i := 0; i < maxLoginTries; i++ { if c.IsSet("sso-passcode") && i == 0
else { credentials["passcode"] = cmd.ui.AskForPassword(passcode.DisplayName) } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentials) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) authenticate(c flags.FlagContext) error { if cmd.config.UAAGrantType() == "client_credentials" { return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again.")) } usernameFlagValue := c.String("u") passwordFlagValue := c.String("p") prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL() if err != nil { return err } passwordKeys := []string{} credentials := make(map[string]string) if value, ok := prompts["username"]; ok { if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" { credentials["username"] = usernameFlagValue } else { credentials["username"] = cmd.ui.Ask(T(value.DisplayName)) } } for key, prompt := range prompts { if prompt.Type == coreconfig.AuthPromptTypePassword { if key == "passcode" || key == "password" { continue } passwordKeys = append(passwordKeys, key) } else if key == "username" { continue } else { credentials[key] = cmd.ui.Ask(T(prompt.DisplayName)) } } for i := 0; i < maxLoginTries; i++ { // ensure that password gets prompted before other codes (eg. mfa code) if passPrompt, ok := prompts["password"]; ok { if passwordFlagValue != "" { credentials["password"] = passwordFlagValue passwordFlagValue = "" } else { credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName)) } } for _, key := range passwordKeys { credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName)) } credentialsCopy := make(map[string]string, len(credentials)) for k, v := range credentials { credentialsCopy[k] = v } cmd.ui.Say(T("Authenticating...")) err = cmd.authenticator.Authenticate(credentialsCopy) if err == nil { cmd.ui.Ok() cmd.ui.Say("") break } cmd.ui.Say(err.Error()) } if err != nil { return errors.New(T("Unable to authenticate.")) } return nil } func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) { orgName := c.String("o") if orgName == "" { orgs, err := cmd.orgRepo.ListOrgs(maxChoices) if err != nil { return false, errors.New(T("Error finding available orgs\n{{.APIErr}}", map[string]interface{}{"APIErr": err.Error()})) } switch len(orgs) { case 0: return false, nil case 1: cmd.targetOrganization(orgs[0]) return true, nil default: orgName = cmd.promptForOrgName(orgs) if orgName == "" { cmd.ui.Say("") return false, nil } } } org, err := cmd.orgRepo.FindByName(orgName) if err != nil { return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}", map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()})) } cmd.targetOrganization(org) return true, nil } func (cmd Login) promptForOrgName(orgs []models.Organization) string { orgNames := []string{} for _, org := range orgs { orgNames = append(orgNames, org.Name) } return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org") } func (cmd Login) targetOrganization(org models.Organization) { cmd.config.SetOrganizationFields(org.OrganizationFields) cmd.ui.Say(T("Targeted org {{.OrgName}}\n", map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)})) } func (cmd Login) setSpace(c flags.FlagContext) error { spaceName := c.String("s") if spaceName == "" { var availableSpaces []models.Space err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool { availableSpaces = append(availableSpaces, space) return (len(availableSpaces) < maxChoices) }) if err != nil { return errors.New(T("Error finding available spaces\n{{.Err}}", map[string]interface{}{"Err": err.Error()})) } if len(availableSpaces) == 0 { return nil } else if len(availableSpaces) == 1 { cmd.targetSpace(availableSpaces[0]) return nil } else { spaceName = cmd.promptForSpaceName(availableSpaces) if spaceName == "" { cmd.ui.Say("") return nil } } } space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { return errors.New(T("Error finding space {{.SpaceName}}\n{{.Err}}", map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()})) } cmd.targetSpace(space) return nil } func (cmd Login) promptForSpaceName(spaces []models.Space) string { spaceNames := []string{} for _, space := range spaces { spaceNames = append(spaceNames, space.Name) } return cmd.promptForName(spaceNames, T("Select a space (or press enter to skip):"), "Space") } func (cmd Login) targetSpace(space models.Space) { cmd.config.SetSpaceFields(space.SpaceFields) cmd.ui.Say(T("Targeted space {{.SpaceName}}\n", map[string]interface{}{"SpaceName": terminal.EntityNameColor(space.Name)})) } func (cmd Login) promptForName(names []string, listPrompt, itemPrompt string) string { nameIndex := 0 var nameString string for nameIndex < 1 || nameIndex > len(names) { var err error // list header cmd.ui.Say(listPrompt) // only display list if it is shorter than maxChoices if len(names) < maxChoices { for i, name := range names { cmd.ui.Say("%d. %s", i+1, name) } } else { cmd.ui.Say(T("There are too many options to display, please type in the name.")) } nameString = cmd.ui.Ask(itemPrompt) if nameString == "" { return "" } nameIndex, err = strconv.Atoi(nameString) if err != nil { nameIndex = 1 return nameString } } return names[nameIndex-1] }
{ credentials["passcode"] = c.String("sso-passcode") }
conditional_block
audio.py
import numpy as np import time from time import perf_counter import matplotlib.pyplot as plt from matplotlib import animation plt.style.use('dark_background') #Librosa from librosa import lpc from librosa.effects import preemphasis from librosa import resample from librosa.util import peak_pick from librosa.util import frame from librosa import load #Scipy from scipy import spatial from scipy.signal import medfilt #Audio import pyaudio import wave import sys #Classes class speech_features: def __init__(self, is_sound, is_voiced, is_lf, is_sonorant): self.is_sound = is_sound self.is_voiced = is_voiced self.is_lf = is_lf self.is_sonorant = is_sonorant #Dicts male_vowel_dict = { (0, 0): " ", (240, 2400): "i", (235, 2100): "y", (390, 2300): "e", (370, 1900): "ø", (610, 1900): "ɛ", (585, 1710): "œ", (850, 1610): "a", (820, 1530): "ɶ", (750, 940): "ɑ", (700, 760): "ɒ", (600, 1170): "ʌ", (500, 700): "ɔ", (460, 1310): "ɤ", (360, 640): "o", (300, 1390): "w", (250, 595): "u" } male_sonorant_dict = { (250, 2200):"l", (150, 1600):"m", (150, 2100):"n", (500, 2400):"r", (3000, 4000):"sh", } male_fricative_dict = { (2000, 5000):"s", (2100, 3000):"z", (4100,0):"sh", (3200,4500):"f", (1500,5500):"j", } images_dict = { " ": "silence.jpeg", "i": "ee.jpg", #Vowels "y": "i-y.jpg", "e": "a-e-i.jpg", "ɛ": "a-e-i.jpg", "œ": "a-e-i.jpg", "a": "a-e-i.jpg", "ɶ": "a-e-i.jpg", "ɑ": "a-e-i.jpg", "ɒ": "a-e-i.jpg", "ʌ": "a-e-i.jpg", "ɔ": "o.jpg", "o": "o.jpg", "ɤ": "u.jpg", "ø": "u.jpg", "w": "u.jpg", "u": "u.jpg", "tpkc": "b-m-p.jpg", #Revisar "bdg": "c-d-g-k-n-s-x-z.jpg", "vz": "f-t-th-v.jpg", "n":"c-d-g-k-n-s-x-z.jpg", #Sonorants "m":"b-m-p.jpg", "l":"l.jpg", "sh":"j-ch-sh.jpg", "r":"r.jpg", "s":"c-d-g-k-n-s-x-z.jpg",#Fricatives "z":"c-d-g-k-n-s-x-z.jpg", "f":"f-t-th-v.jpg", "j":"j-ch-sh.jpg" } NUMBER_OF_SLOTS = 4 def GetPeaks(spectrum, fs, start_freq=150, end_freq=3400): start_indx = int(start_freq*(len(buffer)/fs)) #Start looking from start_freq end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0) return (start_indx+peaks)*(fs/len(buffer)) def FormantsToPhoneme(f1,f2,sex, inv_dict): if sex == "male": keys_array = list(inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] phoneme = inv_dict[keys_array[index]] return phoneme elif sex == "female": #change keys_array = list(male_vowel_inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] vowel = male_vowel_inv_dict[keys_array[index]] return vowel filename = "hello.wav" wf = wave.open(filename, 'rb') fs = wf.getframerate() audio, sr = load(filename) past_status = 'silence' def classifier(speech_features, spectrum, fs, sex="male"): global past_status if speech_features.is_sound: if speech_features.is_voiced: if speech_features
nvoiced if past_status == 'sound': past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=500,end_freq=6500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_fricative_dict) elif past_status == 'silence': past_status = 'sound' return 'tpkc' else: # silence past_status = 'silence' return ' ' #Parameters N = 256 new_fs = 1e4 lpc_order = 14 #Tresholds energy_th = 5e-3 zc_threshold = 150 #FALTA DEFINIR sonorant_th = 50 #FALTA DEFINIR sonorant_zc_th = 20 epsilon = 1e-5 #Window audio samples_n = int(256e-4*sr) frames = frame(audio, samples_n, samples_n, axis=0) images = [] time_taken = [] #Debugging zero_crossings = [] voiced_list = [] phoneme_list = [] ratio_list = [] i=0 for buffer in frames: start_time = perf_counter() is_sound = False # done is_voiced = False # done is_lf = False # done is_sonorant = False windowed_frame = buffer * np.hanning(samples_n) #LPC y espectro hp_filtered = preemphasis(windowed_frame, coef=1) downsampled = resample(hp_filtered, sr, new_fs) coefs = lpc(downsampled, lpc_order) spectrum = 1/abs(np.fft.rfft(coefs,n=N)) # Sound or Silence if windowed_frame.std() < energy_th: is_sound = False else: is_sound = True # High Frequency or Low Frequency zero_crosses = np.nonzero(np.diff(buffer> 0))[0] zero_crosses_count = zero_crosses.size if zero_crosses_count > zc_threshold: is_lf = False else: is_lf = True zero_crossings.append( (i, zero_crosses_count) ) # Voiced or Unvoiced # 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block Nz = zero_crosses_count # 2. Calculate Log energy Es Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer)) # 3. Normalized autocorrelation coefficient at unit sample delay, C1 auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1] C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1])))) # 4. First LPC coefficient (12 poles) FirstLPCcoef = coefs[1] # 5. Normalized prediction error, Ep, expressed in DB sum_exp = 10 error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum Ep = np.dot(error_spectrum,error_spectrum) / (N*N) # LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html # Means and Covariance Matrix silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084]) silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208] ,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425] ,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426] ,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122] ,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]]) unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, 0.5243, -10.9076]) unvoiced_cov = np.array([[1.0000, 0.6059, -0.4069, 0.4648, -0.4603] ,[0.6059, 1.0000, -0.1713, 0.1916, -0.9337] ,[-0.4069, -0.1713, 1.0000, 0.1990, -0.1685] ,[0.4648, 0.1916, 0.1990, 1.0000, -0.2121] ,[-0.4603, -0.9337, -0.1685, -0.2121, 1.0000]]) voiced_mean = np.array([29.1853, -18.3327, 0.9826, 1.1977, -11.1256]) voiced_cov = np.array([[1.0000, -0.2146, -0.8393, -0.3362, 0.3608] ,[-0.2146, 1.0000, 0.1793, 0.6564, -0.7129] ,[-0.8393, 0.1793, 1.0000, 0.3416, -0.5002] ,[-0.3362, 0.6564, 0.3416, 1.0000, -0.4850] ,[0.3608, -0.7129, -0.5002, -0.4850, 1.0000]]) X = np.array([Nz, Es, C1, FirstLPCcoef, Ep]) # Calculate distances (di) #d_silence = np.transpose(X-silence_mean)*np.linalg.inv(silence_cov)*(X-silence_mean) d_unvoiced = np.transpose(X-unvoiced_mean)@np.linalg.inv(unvoiced_cov)@(X-unvoiced_mean) d_voiced = np.transpose(X-voiced_mean)@np.linalg.inv(voiced_cov)@(X-voiced_mean) # Choose minimized distance category if d_unvoiced < d_voiced: is_voiced = False voiced_list.append(0) else: is_voiced = True voiced_list.append(1) # Sonorant or Vowel start_indx = int(640*(len(windowed_frame)/sr)) #Start calculation from 640Hz end_indx = int(2800*(len(windowed_frame)/sr)) #End calculation at 2800Hz low_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy start_indx = int(2000*(len(windowed_frame)/sr)) #Start calculation from 2000Hz end_indx = int(3000*(len(windowed_frame)/sr)) #End calculation at 300Hz high_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy ratio = low_freq_energy / high_freq_energy ratio_list.append(ratio) if (ratio < sonorant_th) and (zero_crosses_count <sonorant_zc_th): is_sonorant = True else: is_sonorant = False # Decision Tree sf = speech_features(is_sound, is_voiced, is_lf, is_sonorant) phoneme = classifier(sf,spectrum, sr) image = images_dict[phoneme] images.append(image) i = i+1 phoneme_list.append(phoneme) time_taken.append(perf_counter() - start_time) CHUNK = int(0.0256*fs) p = pyaudio.PyAudio() path = 'bocas/' stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=fs, output=True) fig = plt.figure() data_im = plt.imread(path +'silence.jpeg') im = plt.imshow(data_im) im.set_data(data_im) plt.draw() plt.pause(1) data = wf.readframes(CHUNK) while data != b'': data_im = plt.imread(path+images.pop(0)) im.set_data(data_im) plt.draw() plt.pause(0.000000000000000000000001) stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()
.is_lf: if past_status == 'sound': if speech_features.is_sonorant: past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=100,end_freq=4500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_sonorant_dict) else: # vowel past_status = 'sound' formants = GetPeaks(spectrum, fs) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_vowel_dict) elif past_status == 'silence': past_status = 'sound' return 'bdg' else: # hf past_status = 'sound' return 'vz' else: # u
conditional_block
audio.py
import numpy as np import time from time import perf_counter import matplotlib.pyplot as plt from matplotlib import animation plt.style.use('dark_background') #Librosa from librosa import lpc from librosa.effects import preemphasis from librosa import resample from librosa.util import peak_pick from librosa.util import frame from librosa import load #Scipy from scipy import spatial from scipy.signal import medfilt #Audio import pyaudio import wave import sys #Classes class speech_features: def __init__(self, is_sound, is_voiced, is_lf, is_sonorant): self.is_sound = is_sound self.is_voiced = is_voiced self.is_lf = is_lf self.is_sonorant = is_sonorant #Dicts male_vowel_dict = { (0, 0): " ", (240, 2400): "i", (235, 2100): "y", (390, 2300): "e", (370, 1900): "ø", (610, 1900): "ɛ", (585, 1710): "œ", (850, 1610): "a", (820, 1530): "ɶ", (750, 940): "ɑ", (700, 760): "ɒ", (600, 1170): "ʌ", (500, 700): "ɔ", (460, 1310): "ɤ", (360, 640): "o", (300, 1390): "w", (250, 595): "u" } male_sonorant_dict = { (250, 2200):"l", (150, 1600):"m", (150, 2100):"n", (500, 2400):"r", (3000, 4000):"sh", } male_fricative_dict = { (2000, 5000):"s", (2100, 3000):"z", (4100,0):"sh", (3200,4500):"f", (1500,5500):"j", } images_dict = { " ": "silence.jpeg", "i": "ee.jpg", #Vowels "y": "i-y.jpg", "e": "a-e-i.jpg", "ɛ": "a-e-i.jpg", "œ": "a-e-i.jpg", "a": "a-e-i.jpg", "ɶ": "a-e-i.jpg", "ɑ": "a-e-i.jpg", "ɒ": "a-e-i.jpg", "ʌ": "a-e-i.jpg", "ɔ": "o.jpg", "o": "o.jpg", "ɤ": "u.jpg", "ø": "u.jpg", "w": "u.jpg", "u": "u.jpg", "tpkc": "b-m-p.jpg", #Revisar "bdg": "c-d-g-k-n-s-x-z.jpg", "vz": "f-t-th-v.jpg", "n":"c-d-g-k-n-s-x-z.jpg", #Sonorants "m":"b-m-p.jpg", "l":"l.jpg", "sh":"j-ch-sh.jpg", "r":"r.jpg", "s":"c-d-g-k-n-s-x-z.jpg",#Fricatives "z":"c-d-g-k-n-s-x-z.jpg", "f":"f-t-th-v.jpg", "j":"j-ch-sh.jpg" } NUMBER_OF_SLOTS = 4 def GetPeaks(spectrum, fs, start_freq=150, end_freq=3400): start_indx = int(s
oneme(f1,f2,sex, inv_dict): if sex == "male": keys_array = list(inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] phoneme = inv_dict[keys_array[index]] return phoneme elif sex == "female": #change keys_array = list(male_vowel_inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] vowel = male_vowel_inv_dict[keys_array[index]] return vowel filename = "hello.wav" wf = wave.open(filename, 'rb') fs = wf.getframerate() audio, sr = load(filename) past_status = 'silence' def classifier(speech_features, spectrum, fs, sex="male"): global past_status if speech_features.is_sound: if speech_features.is_voiced: if speech_features.is_lf: if past_status == 'sound': if speech_features.is_sonorant: past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=100,end_freq=4500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_sonorant_dict) else: # vowel past_status = 'sound' formants = GetPeaks(spectrum, fs) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_vowel_dict) elif past_status == 'silence': past_status = 'sound' return 'bdg' else: # hf past_status = 'sound' return 'vz' else: # unvoiced if past_status == 'sound': past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=500,end_freq=6500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_fricative_dict) elif past_status == 'silence': past_status = 'sound' return 'tpkc' else: # silence past_status = 'silence' return ' ' #Parameters N = 256 new_fs = 1e4 lpc_order = 14 #Tresholds energy_th = 5e-3 zc_threshold = 150 #FALTA DEFINIR sonorant_th = 50 #FALTA DEFINIR sonorant_zc_th = 20 epsilon = 1e-5 #Window audio samples_n = int(256e-4*sr) frames = frame(audio, samples_n, samples_n, axis=0) images = [] time_taken = [] #Debugging zero_crossings = [] voiced_list = [] phoneme_list = [] ratio_list = [] i=0 for buffer in frames: start_time = perf_counter() is_sound = False # done is_voiced = False # done is_lf = False # done is_sonorant = False windowed_frame = buffer * np.hanning(samples_n) #LPC y espectro hp_filtered = preemphasis(windowed_frame, coef=1) downsampled = resample(hp_filtered, sr, new_fs) coefs = lpc(downsampled, lpc_order) spectrum = 1/abs(np.fft.rfft(coefs,n=N)) # Sound or Silence if windowed_frame.std() < energy_th: is_sound = False else: is_sound = True # High Frequency or Low Frequency zero_crosses = np.nonzero(np.diff(buffer> 0))[0] zero_crosses_count = zero_crosses.size if zero_crosses_count > zc_threshold: is_lf = False else: is_lf = True zero_crossings.append( (i, zero_crosses_count) ) # Voiced or Unvoiced # 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block Nz = zero_crosses_count # 2. Calculate Log energy Es Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer)) # 3. Normalized autocorrelation coefficient at unit sample delay, C1 auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1] C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1])))) # 4. First LPC coefficient (12 poles) FirstLPCcoef = coefs[1] # 5. Normalized prediction error, Ep, expressed in DB sum_exp = 10 error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum Ep = np.dot(error_spectrum,error_spectrum) / (N*N) # LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html # Means and Covariance Matrix silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084]) silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208] ,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425] ,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426] ,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122] ,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]]) unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, 0.5243, -10.9076]) unvoiced_cov = np.array([[1.0000, 0.6059, -0.4069, 0.4648, -0.4603] ,[0.6059, 1.0000, -0.1713, 0.1916, -0.9337] ,[-0.4069, -0.1713, 1.0000, 0.1990, -0.1685] ,[0.4648, 0.1916, 0.1990, 1.0000, -0.2121] ,[-0.4603, -0.9337, -0.1685, -0.2121, 1.0000]]) voiced_mean = np.array([29.1853, -18.3327, 0.9826, 1.1977, -11.1256]) voiced_cov = np.array([[1.0000, -0.2146, -0.8393, -0.3362, 0.3608] ,[-0.2146, 1.0000, 0.1793, 0.6564, -0.7129] ,[-0.8393, 0.1793, 1.0000, 0.3416, -0.5002] ,[-0.3362, 0.6564, 0.3416, 1.0000, -0.4850] ,[0.3608, -0.7129, -0.5002, -0.4850, 1.0000]]) X = np.array([Nz, Es, C1, FirstLPCcoef, Ep]) # Calculate distances (di) #d_silence = np.transpose(X-silence_mean)*np.linalg.inv(silence_cov)*(X-silence_mean) d_unvoiced = np.transpose(X-unvoiced_mean)@np.linalg.inv(unvoiced_cov)@(X-unvoiced_mean) d_voiced = np.transpose(X-voiced_mean)@np.linalg.inv(voiced_cov)@(X-voiced_mean) # Choose minimized distance category if d_unvoiced < d_voiced: is_voiced = False voiced_list.append(0) else: is_voiced = True voiced_list.append(1) # Sonorant or Vowel start_indx = int(640*(len(windowed_frame)/sr)) #Start calculation from 640Hz end_indx = int(2800*(len(windowed_frame)/sr)) #End calculation at 2800Hz low_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy start_indx = int(2000*(len(windowed_frame)/sr)) #Start calculation from 2000Hz end_indx = int(3000*(len(windowed_frame)/sr)) #End calculation at 300Hz high_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy ratio = low_freq_energy / high_freq_energy ratio_list.append(ratio) if (ratio < sonorant_th) and (zero_crosses_count <sonorant_zc_th): is_sonorant = True else: is_sonorant = False # Decision Tree sf = speech_features(is_sound, is_voiced, is_lf, is_sonorant) phoneme = classifier(sf,spectrum, sr) image = images_dict[phoneme] images.append(image) i = i+1 phoneme_list.append(phoneme) time_taken.append(perf_counter() - start_time) CHUNK = int(0.0256*fs) p = pyaudio.PyAudio() path = 'bocas/' stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=fs, output=True) fig = plt.figure() data_im = plt.imread(path +'silence.jpeg') im = plt.imshow(data_im) im.set_data(data_im) plt.draw() plt.pause(1) data = wf.readframes(CHUNK) while data != b'': data_im = plt.imread(path+images.pop(0)) im.set_data(data_im) plt.draw() plt.pause(0.000000000000000000000001) stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()
tart_freq*(len(buffer)/fs)) #Start looking from start_freq end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0) return (start_indx+peaks)*(fs/len(buffer)) def FormantsToPh
identifier_body
audio.py
import numpy as np import time from time import perf_counter import matplotlib.pyplot as plt from matplotlib import animation plt.style.use('dark_background') #Librosa from librosa import lpc from librosa.effects import preemphasis from librosa import resample from librosa.util import peak_pick from librosa.util import frame from librosa import load #Scipy from scipy import spatial from scipy.signal import medfilt #Audio import pyaudio import wave import sys #Classes class speech_features: def __init__(self, is_sound, is_voiced, is_lf, is_sonorant): self.is_sound = is_sound self.is_voiced = is_voiced self.is_lf = is_lf self.is_sonorant = is_sonorant #Dicts male_vowel_dict = { (0, 0): " ", (240, 2400): "i", (235, 2100): "y", (390, 2300): "e", (370, 1900): "ø", (610, 1900): "ɛ", (585, 1710): "œ", (850, 1610): "a", (820, 1530): "ɶ", (750, 940): "ɑ", (700, 760): "ɒ", (600, 1170): "ʌ", (500, 700): "ɔ", (460, 1310): "ɤ", (360, 640): "o", (300, 1390): "w", (250, 595): "u" } male_sonorant_dict = { (250, 2200):"l", (150, 1600):"m", (150, 2100):"n", (500, 2400):"r", (3000, 4000):"sh", } male_fricative_dict = { (2000, 5000):"s", (2100, 3000):"z", (4100,0):"sh", (3200,4500):"f", (1500,5500):"j", } images_dict = { " ": "silence.jpeg", "i": "ee.jpg", #Vowels "y": "i-y.jpg", "e": "a-e-i.jpg", "ɛ": "a-e-i.jpg", "œ": "a-e-i.jpg", "a": "a-e-i.jpg", "ɶ": "a-e-i.jpg", "ɑ": "a-e-i.jpg", "ɒ": "a-e-i.jpg", "ʌ": "a-e-i.jpg", "ɔ": "o.jpg", "o": "o.jpg", "ɤ": "u.jpg", "ø": "u.jpg", "w": "u.jpg", "u": "u.jpg", "tpkc": "b-m-p.jpg", #Revisar "bdg": "c-d-g-k-n-s-x-z.jpg", "vz": "f-t-th-v.jpg", "n":"c-d-g-k-n-s-x-z.jpg", #Sonorants "m":"b-m-p.jpg", "l":"l.jpg", "sh":"j-ch-sh.jpg", "r":"r.jpg", "s":"c-d-g-k-n-s-x-z.jpg",#Fricatives "z":"c-d-g-k-n-s-x-z.jpg", "f":"f-t-th-v.jpg", "j":"j-ch-sh.jpg" } NUMBER_OF_SLOTS = 4 def GetPeaks(spectrum, fs, start_freq=150, end_freq=3400): start_indx = int(start_freq*(len(buffer)/fs)) #Start looking from start_freq end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0) return (start_indx+peaks)*(fs/len(buffer)) def FormantsToPhoneme(f1,f2,sex, inv_dict): if sex == "male": keys_array = list(inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] phoneme = inv_dict[keys_array[index]] return phoneme elif sex == "female": #change keys_array = list(male_vowel_inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] vowel = male_vowel_inv_dict[keys_array[index]] return vowel filename = "hello.wav" wf = wave.open(filename, 'rb') fs = wf.getframerate() audio, sr = load(filename) past_status = 'silence' def classifier(speech_features, spectrum, fs, sex="male"): global past_status if speech_features.is_sound: if speech_features.is_voiced: if speech_features.is_lf: if past_status == 'sound': if speech_features.is_sonorant: past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=100,end_freq=4500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_sonorant_dict) else: # vowel past_status = 'sound' formants = GetPeaks(spectrum, fs) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_vowel_dict) elif past_status == 'silence': past_status = 'sound' return 'bdg' else: # hf past_status = 'sound' return 'vz' else: # unvoiced if past_status == 'sound': past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=500,end_freq=6500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_fricative_dict) elif past_status == 'silence': past_status = 'sound' return 'tpkc' else: # silence past_status = 'silence' return ' ' #Parameters N = 256 new_fs = 1e4 lpc_order = 14 #Tresholds energy_th = 5e-3 zc_threshold = 150 #FALTA DEFINIR sonorant_th = 50 #FALTA DEFINIR sonorant_zc_th = 20 epsilon = 1e-5 #Window audio samples_n = int(256e-4*sr) frames = frame(audio, samples_n, samples_n, axis=0) images = [] time_taken = [] #Debugging zero_crossings = [] voiced_list = [] phoneme_list = [] ratio_list = [] i=0 for buffer in frames: start_time = perf_counter() is_sound = False # done is_voiced = False # done is_lf = False # done is_sonorant = False windowed_frame = buffer * np.hanning(samples_n) #LPC y espectro hp_filtered = preemphasis(windowed_frame, coef=1) downsampled = resample(hp_filtered, sr, new_fs) coefs = lpc(downsampled, lpc_order) spectrum = 1/abs(np.fft.rfft(coefs,n=N)) # Sound or Silence if windowed_frame.std() < energy_th: is_sound = False else: is_sound = True # High Frequency or Low Frequency zero_crosses = np.nonzero(np.diff(buffer> 0))[0] zero_crosses_count = zero_crosses.size if zero_crosses_count > zc_threshold: is_lf = False else: is_lf = True zero_crossings.append( (i, zero_crosses_count) ) # Voiced or Unvoiced # 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block Nz = zero_crosses_count # 2. Calculate Log energy Es Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer)) # 3. Normalized autocorrelation coefficient at unit sample delay, C1 auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1] C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1])))) # 4. First LPC coefficient (12 poles) FirstLPCcoef = coefs[1] # 5. Normalized prediction error, Ep, expressed in DB sum_exp = 10 error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum Ep = np.dot(error_spectrum,error_spectrum) / (N*N) # LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html # Means and Covariance Matrix silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084]) silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208] ,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425] ,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426] ,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122] ,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]]) unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, 0.5243, -10.9076]) unvoiced_cov = np.array([[1.0000, 0.6059, -0.4069, 0.4648, -0.4603] ,[0.6059, 1.0000, -0.1713, 0.1916, -0.9337] ,[-0.4069, -0.1713, 1.0000, 0.1990, -0.1685] ,[0.4648, 0.1916, 0.1990, 1.0000, -0.2121] ,[-0.4603, -0.9337, -0.1685, -0.2121, 1.0000]]) voiced_mean = np.array([29.1853, -18.3327, 0.9826, 1.1977, -11.1256]) voiced_cov = np.array([[1.0000, -0.2146, -0.8393, -0.3362, 0.3608] ,[-0.2146, 1.0000, 0.1793, 0.6564, -0.7129] ,[-0.8393, 0.1793, 1.0000, 0.3416, -0.5002] ,[-0.3362, 0.6564, 0.3416, 1.0000, -0.4850] ,[0.3608, -0.7129, -0.5002, -0.4850, 1.0000]]) X = np.array([Nz, Es, C1, FirstLPCcoef, Ep]) # Calculate distances (di) #d_silence = np.transpose(X-silence_mean)*np.linalg.inv(silence_cov)*(X-silence_mean) d_unvoiced = np.transpose(X-unvoiced_mean)@np.linalg.inv(unvoiced_cov)@(X-unvoiced_mean) d_voiced = np.transpose(X-voiced_mean)@np.linalg.inv(voiced_cov)@(X-voiced_mean) # Choose minimized distance category if d_unvoiced < d_voiced: is_voiced = False voiced_list.append(0) else: is_voiced = True voiced_list.append(1) # Sonorant or Vowel start_indx = int(640*(len(windowed_frame)/sr)) #Start calculation from 640Hz end_indx = int(2800*(len(windowed_frame)/sr)) #End calculation at 2800Hz low_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy
ratio = low_freq_energy / high_freq_energy ratio_list.append(ratio) if (ratio < sonorant_th) and (zero_crosses_count <sonorant_zc_th): is_sonorant = True else: is_sonorant = False # Decision Tree sf = speech_features(is_sound, is_voiced, is_lf, is_sonorant) phoneme = classifier(sf,spectrum, sr) image = images_dict[phoneme] images.append(image) i = i+1 phoneme_list.append(phoneme) time_taken.append(perf_counter() - start_time) CHUNK = int(0.0256*fs) p = pyaudio.PyAudio() path = 'bocas/' stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=fs, output=True) fig = plt.figure() data_im = plt.imread(path +'silence.jpeg') im = plt.imshow(data_im) im.set_data(data_im) plt.draw() plt.pause(1) data = wf.readframes(CHUNK) while data != b'': data_im = plt.imread(path+images.pop(0)) im.set_data(data_im) plt.draw() plt.pause(0.000000000000000000000001) stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()
start_indx = int(2000*(len(windowed_frame)/sr)) #Start calculation from 2000Hz end_indx = int(3000*(len(windowed_frame)/sr)) #End calculation at 300Hz high_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy
random_line_split
audio.py
import numpy as np import time from time import perf_counter import matplotlib.pyplot as plt from matplotlib import animation plt.style.use('dark_background') #Librosa from librosa import lpc from librosa.effects import preemphasis from librosa import resample from librosa.util import peak_pick from librosa.util import frame from librosa import load #Scipy from scipy import spatial from scipy.signal import medfilt #Audio import pyaudio import wave import sys #Classes class speech_features: def __init__(self, is_sound, is_voiced, is_lf, is_sonorant): self.is_sound = is_sound self.is_voiced = is_voiced self.is_lf = is_lf self.is_sonorant = is_sonorant #Dicts male_vowel_dict = { (0, 0): " ", (240, 2400): "i", (235, 2100): "y", (390, 2300): "e", (370, 1900): "ø", (610, 1900): "ɛ", (585, 1710): "œ", (850, 1610): "a", (820, 1530): "ɶ", (750, 940): "ɑ", (700, 760): "ɒ", (600, 1170): "ʌ", (500, 700): "ɔ", (460, 1310): "ɤ", (360, 640): "o", (300, 1390): "w", (250, 595): "u" } male_sonorant_dict = { (250, 2200):"l", (150, 1600):"m", (150, 2100):"n", (500, 2400):"r", (3000, 4000):"sh", } male_fricative_dict = { (2000, 5000):"s", (2100, 3000):"z", (4100,0):"sh", (3200,4500):"f", (1500,5500):"j", } images_dict = { " ": "silence.jpeg", "i": "ee.jpg", #Vowels "y": "i-y.jpg", "e": "a-e-i.jpg", "ɛ": "a-e-i.jpg", "œ": "a-e-i.jpg", "a": "a-e-i.jpg", "ɶ": "a-e-i.jpg", "ɑ": "a-e-i.jpg", "ɒ": "a-e-i.jpg", "ʌ": "a-e-i.jpg", "ɔ": "o.jpg", "o": "o.jpg", "ɤ": "u.jpg", "ø": "u.jpg", "w": "u.jpg", "u": "u.jpg", "tpkc": "b-m-p.jpg", #Revisar "bdg": "c-d-g-k-n-s-x-z.jpg", "vz": "f-t-th-v.jpg", "n":"c-d-g-k-n-s-x-z.jpg", #Sonorants "m":"b-m-p.jpg", "l":"l.jpg", "sh":"j-ch-sh.jpg", "r":"r.jpg", "s":"c-d-g-k-n-s-x-z.jpg",#Fricatives "z":"c-d-g-k-n-s-x-z.jpg", "f":"f-t-th-v.jpg", "j":"j-ch-sh.jpg" } NUMBER_OF_SLOTS = 4 def GetPeaks(spectrum,
rt_freq=150, end_freq=3400): start_indx = int(start_freq*(len(buffer)/fs)) #Start looking from start_freq end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0) return (start_indx+peaks)*(fs/len(buffer)) def FormantsToPhoneme(f1,f2,sex, inv_dict): if sex == "male": keys_array = list(inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] phoneme = inv_dict[keys_array[index]] return phoneme elif sex == "female": #change keys_array = list(male_vowel_inv_dict.keys()) tree = spatial.KDTree(keys_array) index = tree.query([(f1,f2)])[1][0] vowel = male_vowel_inv_dict[keys_array[index]] return vowel filename = "hello.wav" wf = wave.open(filename, 'rb') fs = wf.getframerate() audio, sr = load(filename) past_status = 'silence' def classifier(speech_features, spectrum, fs, sex="male"): global past_status if speech_features.is_sound: if speech_features.is_voiced: if speech_features.is_lf: if past_status == 'sound': if speech_features.is_sonorant: past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=100,end_freq=4500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_sonorant_dict) else: # vowel past_status = 'sound' formants = GetPeaks(spectrum, fs) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_vowel_dict) elif past_status == 'silence': past_status = 'sound' return 'bdg' else: # hf past_status = 'sound' return 'vz' else: # unvoiced if past_status == 'sound': past_status = 'sound' formants = GetPeaks(spectrum, fs, start_freq=500,end_freq=6500) F1 = formants[0] F2 = formants[1] return FormantsToPhoneme(F1,F2,sex, male_fricative_dict) elif past_status == 'silence': past_status = 'sound' return 'tpkc' else: # silence past_status = 'silence' return ' ' #Parameters N = 256 new_fs = 1e4 lpc_order = 14 #Tresholds energy_th = 5e-3 zc_threshold = 150 #FALTA DEFINIR sonorant_th = 50 #FALTA DEFINIR sonorant_zc_th = 20 epsilon = 1e-5 #Window audio samples_n = int(256e-4*sr) frames = frame(audio, samples_n, samples_n, axis=0) images = [] time_taken = [] #Debugging zero_crossings = [] voiced_list = [] phoneme_list = [] ratio_list = [] i=0 for buffer in frames: start_time = perf_counter() is_sound = False # done is_voiced = False # done is_lf = False # done is_sonorant = False windowed_frame = buffer * np.hanning(samples_n) #LPC y espectro hp_filtered = preemphasis(windowed_frame, coef=1) downsampled = resample(hp_filtered, sr, new_fs) coefs = lpc(downsampled, lpc_order) spectrum = 1/abs(np.fft.rfft(coefs,n=N)) # Sound or Silence if windowed_frame.std() < energy_th: is_sound = False else: is_sound = True # High Frequency or Low Frequency zero_crosses = np.nonzero(np.diff(buffer> 0))[0] zero_crosses_count = zero_crosses.size if zero_crosses_count > zc_threshold: is_lf = False else: is_lf = True zero_crossings.append( (i, zero_crosses_count) ) # Voiced or Unvoiced # 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block Nz = zero_crosses_count # 2. Calculate Log energy Es Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer)) # 3. Normalized autocorrelation coefficient at unit sample delay, C1 auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1] C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1])))) # 4. First LPC coefficient (12 poles) FirstLPCcoef = coefs[1] # 5. Normalized prediction error, Ep, expressed in DB sum_exp = 10 error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum Ep = np.dot(error_spectrum,error_spectrum) / (N*N) # LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html # Means and Covariance Matrix silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084]) silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208] ,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425] ,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426] ,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122] ,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]]) unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, 0.5243, -10.9076]) unvoiced_cov = np.array([[1.0000, 0.6059, -0.4069, 0.4648, -0.4603] ,[0.6059, 1.0000, -0.1713, 0.1916, -0.9337] ,[-0.4069, -0.1713, 1.0000, 0.1990, -0.1685] ,[0.4648, 0.1916, 0.1990, 1.0000, -0.2121] ,[-0.4603, -0.9337, -0.1685, -0.2121, 1.0000]]) voiced_mean = np.array([29.1853, -18.3327, 0.9826, 1.1977, -11.1256]) voiced_cov = np.array([[1.0000, -0.2146, -0.8393, -0.3362, 0.3608] ,[-0.2146, 1.0000, 0.1793, 0.6564, -0.7129] ,[-0.8393, 0.1793, 1.0000, 0.3416, -0.5002] ,[-0.3362, 0.6564, 0.3416, 1.0000, -0.4850] ,[0.3608, -0.7129, -0.5002, -0.4850, 1.0000]]) X = np.array([Nz, Es, C1, FirstLPCcoef, Ep]) # Calculate distances (di) #d_silence = np.transpose(X-silence_mean)*np.linalg.inv(silence_cov)*(X-silence_mean) d_unvoiced = np.transpose(X-unvoiced_mean)@np.linalg.inv(unvoiced_cov)@(X-unvoiced_mean) d_voiced = np.transpose(X-voiced_mean)@np.linalg.inv(voiced_cov)@(X-voiced_mean) # Choose minimized distance category if d_unvoiced < d_voiced: is_voiced = False voiced_list.append(0) else: is_voiced = True voiced_list.append(1) # Sonorant or Vowel start_indx = int(640*(len(windowed_frame)/sr)) #Start calculation from 640Hz end_indx = int(2800*(len(windowed_frame)/sr)) #End calculation at 2800Hz low_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy start_indx = int(2000*(len(windowed_frame)/sr)) #Start calculation from 2000Hz end_indx = int(3000*(len(windowed_frame)/sr)) #End calculation at 300Hz high_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy ratio = low_freq_energy / high_freq_energy ratio_list.append(ratio) if (ratio < sonorant_th) and (zero_crosses_count <sonorant_zc_th): is_sonorant = True else: is_sonorant = False # Decision Tree sf = speech_features(is_sound, is_voiced, is_lf, is_sonorant) phoneme = classifier(sf,spectrum, sr) image = images_dict[phoneme] images.append(image) i = i+1 phoneme_list.append(phoneme) time_taken.append(perf_counter() - start_time) CHUNK = int(0.0256*fs) p = pyaudio.PyAudio() path = 'bocas/' stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=fs, output=True) fig = plt.figure() data_im = plt.imread(path +'silence.jpeg') im = plt.imshow(data_im) im.set_data(data_im) plt.draw() plt.pause(1) data = wf.readframes(CHUNK) while data != b'': data_im = plt.imread(path+images.pop(0)) im.set_data(data_im) plt.draw() plt.pause(0.000000000000000000000001) stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate()
fs, sta
identifier_name
main.py
try: from packages.telegram_hundlers import telegramHundlers from aiogram import Bot, Dispatcher, executor import asyncio from threading import Thread import time from copy import deepcopy from cfscrape import create_scraper import os from packages.load_data import loadInStrings, loadInTxt, Struct, load_settings from packages.logger import log_handler, logger from packages.data import URL as _URL from packages.data import Payload as _Payload from packages.mw_sql import baseUniversal from packages._utils import _utils from packages.telegram_hundlers import telegramHundlers except ImportError as e: print(f"ImportError: {e}") print("RU: Установите библиотеки и попробуйте снова.") print("**Запустите файл install_packages.bat в папке install чтобы автоматически установить библиотеки") print("EN: Please install packages and try again.") print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.") input() quit() banner = """ _______________________________________________________________________ | | | __ ___ __ __ ____ | | \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ | | \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| | | \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | | | \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| | | | | _ _ _ _ | | | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ | | | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ | | | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ | | |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| | | |___/ | |_______________________________________________________________________| """ print(banner) # message limit (must be lower then 4096) message_limit = 2048 # path settings_path = os.path.realpath('.') + '/settings.txt' accounts_path = os.path.realpath('.') + '/db/accounts.txt' db_path = os.path.realpath('.') + '/db/accounts.db' log_path = os.path.realpath('.') + '/parser.log' timer_path = os.path.realpath('.') + '/db/timer.json' # scraper = create_scraper() _log = logger(name='WAXParser', file=log_path, level='INFO').get_logger() log = log_handler(_log).log base = baseUniversal(db_path) # settings and other data URL = _URL() Payload = _Payload() limits_notifications = deepcopy(Payload.limits_notifications) settings = loadInTxt().get(settings_path) settings = Struct(**settings) _u = _utils(settings, base, _log, log, scraper, URL, Payload) # validate settings if not settings.bot_token or\ not settings.user_id: log('Fill bot_token and user_id in settings.txt and restart') input() quit() # telegram bot = Bot(token=settings.bot_token)
asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa) async def send_to_all_ids(text): uzs = _u.get_user_ids() for u in uzs: try: await send_reply(text, u) except Exception as e: print(f'send_to_all_ids error: {e}') async def send_reply(text, user_id): try: text = str(text) if not text: text = 'Empty message' if len(text) > message_limit: for x in _u.split_text(text, message_limit): await bot.send_message(user_id, x, parse_mode='html', disable_web_page_preview=True) else: await bot.send_message(user_id, text, parse_mode='html', disable_web_page_preview=True) except Exception as e: _log.exception(f'send_reply error: {repr(e)}') def parser(settings, limits_notifications): notification( f"<b>WAXParser started.\n" f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n" f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n" f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n" f"Tokens_notifications: {settings.tokens_notifications}\n" f"NFTs_notifications: {settings.nfts_notifications}</b>" ) while True: accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path) accounts_db = _u.get_accounts(whitelist=accounts) for account in accounts: acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path) if account not in acs: continue log('fetching...', account) settings = loadInTxt().get(settings_path) settings = Struct(**settings) if account not in accounts_db.keys(): accounts_db[account] = deepcopy(Payload.defoult_account_data) base.add( table='accounts', name=account, assets=[], tokens=accounts_db[account]['tokens'] ) tokens_last = accounts_db[account]['tokens'] err, tokens = _u.get_tokens(scraper, account, tokens_last) if err: _log.error(err) nfts_last = accounts_db[account]['assets'] err, assets = _u.get_nfts(scraper, account, nfts_last) if err: _log.error(err) resourses = _u.get_resourses(account) #print(resourses) if resourses['cpu_staked'] is not None: tokens['CPU_STAKED'] = resourses['cpu_staked'] else: if 'cpu_staked' in accounts_db[account]['tokens'].keys(): tokens['CPU_STAKED'] = accounts_db[account]['tokens']['cpu_staked'] # check tokens if tokens != accounts_db[account]['tokens']: # add new token or balance changed for k, v in tokens.items(): if k not in accounts_db[account]['tokens'].keys(): accounts_db[account]['tokens'][k] = v text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>' if settings.tokens_notifications == 'true': notification(text) log(f'{account} new token deposit to your wallet: {k}: {v}') _u.update_timer(k, round(v, 5)) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) else: for k1, v1 in tokens.items(): if v1 != accounts_db[account]['tokens'][k1]: if v1 > accounts_db[account]['tokens'][k1]: log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]") _u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5)) text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>" if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM': notification( f"<b>Account: {account}\n"\ f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\ f"Seems like account was banned...</b>" ) accounts_db[account]['tokens'][k1] = v1 else: log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]") text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>" accounts_db[account]['tokens'][k1] = v1 if settings.tokens_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) # check assets if assets != accounts_db[account]['assets']: # add or delete assets new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']] del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets] if new_assets: text = f"<b>Account: <code>{account}</code></b>\n" _price_sum = 0 for ass in new_assets: parsed = _u.fetch_asset(ass) if not parsed['success']: continue price = _u.get_price(parsed['template_id'], parsed['name']) log(f"{account} new asset: {ass} {parsed['name']} ({price} WAX)") text += f"<b>[{ass}] {parsed['name']} - {price} WAX</b>\n" _price_sum += price text += f"\n<b>+{round(_price_sum, 2)} WAX</b>" if settings.nfts_notifications == 'true': notification(text) elif del_assets: text = f"<b>Account: <code>{account}</code></b>\n" + '\n'.join(del_assets) log(f"{account} transfer NFTs: {' '.join(del_assets)}") if settings.nfts_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], assets=list(assets)) # check account resourses for _res in resourses.keys(): if 'stake' in _res: continue if resourses[_res] > int(settings.get(_res+'_limit')): limits_notifications, is_time_res = _u.is_time_to_notif(limits_notifications, _res, account, settings['out_of_limit_timeout']) if is_time_res: notification(f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>") log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%).") if settings.timeout: time.sleep(int(settings.timeout)) else: time.sleep(10) # start thread def start(settings, limits_notifications): while True: try: parser(settings, limits_notifications) except Exception as e: _log.exception("MainError: ") if __name__ == '__main__': Thread(target=start, args=(settings, limits_notifications,)).start() hundlers = telegramHundlers(dp, zalupa, send_reply, _u, base, executor, settings_path, accounts_path) hundlers.register_all_methods() hundlers.run() # кто прочитал тот сдохнет :)
dp = Dispatcher(bot) zalupa = asyncio.new_event_loop() def notification(text):
random_line_split
main.py
try: from packages.telegram_hundlers import telegramHundlers from aiogram import Bot, Dispatcher, executor import asyncio from threading import Thread import time from copy import deepcopy from cfscrape import create_scraper import os from packages.load_data import loadInStrings, loadInTxt, Struct, load_settings from packages.logger import log_handler, logger from packages.data import URL as _URL from packages.data import Payload as _Payload from packages.mw_sql import baseUniversal from packages._utils import _utils from packages.telegram_hundlers import telegramHundlers except ImportError as e: print(f"ImportError: {e}") print("RU: Установите библиотеки и попробуйте снова.") print("**Запустите файл install_packages.bat в папке install чтобы автоматически установить библиотеки") print("EN: Please install packages and try again.") print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.") input() quit() banner = """ _______________________________________________________________________ | | | __ ___ __ __ ____ | | \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ | | \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| | | \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | | | \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| | | | | _ _ _ _ | | | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ | | | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ | | | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ | | |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| | | |___/ | |_______________________________________________________________________| """ print(banner) # message limit (must be lower then 4096) message_limit = 2048 # path settings_path = os.path.realpath('.') + '/settings.txt' accounts_path = os.path.realpath('.') + '/db/accounts.txt' db_path = os.path.realpath('.') + '/db/accounts.db' log_path = os.path.realpath('.') + '/parser.log' timer_path = os.path.realpath('.') + '/db/timer.json' # scraper = create_scraper() _log = logger(name='WAXParser', file=log_path, level='INFO').get_logger() log = log_handler(_log).log base = baseUniversal(db_path) # settings and other data URL = _URL() Payload = _Payload() limits_notifications = deepcopy(Payload.limits_notifications) settings = loadInTxt().get(settings_path) settings = Struct(**settings) _u = _utils(settings, base, _log, log, scraper, URL, Payload) # validate settings if not settings.bot_token or\ not settings.user_id: log('Fill bot_token and user_id in settings.txt and restart') input() quit() # telegram bot = Bot(token=settings.bot_token) dp = Dispatcher(bot) zalupa = asyncio.new_event_loop() def notification(text): asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa) asyn
o_all_ids(text): uzs = _u.get_user_ids() for u in uzs: try: await send_reply(text, u) except Exception as e: print(f'send_to_all_ids error: {e}') async def send_reply(text, user_id): try: text = str(text) if not text: text = 'Empty message' if len(text) > message_limit: for x in _u.split_text(text, message_limit): await bot.send_message(user_id, x, parse_mode='html', disable_web_page_preview=True) else: await bot.send_message(user_id, text, parse_mode='html', disable_web_page_preview=True) except Exception as e: _log.exception(f'send_reply error: {repr(e)}') def parser(settings, limits_notifications): notification( f"<b>WAXParser started.\n" f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n" f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n" f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n" f"Tokens_notifications: {settings.tokens_notifications}\n" f"NFTs_notifications: {settings.nfts_notifications}</b>" ) while True: accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path) accounts_db = _u.get_accounts(whitelist=accounts) for account in accounts: acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path) if account not in acs: continue log('fetching...', account) settings = loadInTxt().get(settings_path) settings = Struct(**settings) if account not in accounts_db.keys(): accounts_db[account] = deepcopy(Payload.defoult_account_data) base.add( table='accounts', name=account, assets=[], tokens=accounts_db[account]['tokens'] ) tokens_last = accounts_db[account]['tokens'] err, tokens = _u.get_tokens(scraper, account, tokens_last) if err: _log.error(err) nfts_last = accounts_db[account]['assets'] err, assets = _u.get_nfts(scraper, account, nfts_last) if err: _log.error(err) resourses = _u.get_resourses(account) #print(resourses) if resourses['cpu_staked'] is not None: tokens['CPU_STAKED'] = resourses['cpu_staked'] else: if 'cpu_staked' in accounts_db[account]['tokens'].keys(): tokens['CPU_STAKED'] = accounts_db[account]['tokens']['cpu_staked'] # check tokens if tokens != accounts_db[account]['tokens']: # add new token or balance changed for k, v in tokens.items(): if k not in accounts_db[account]['tokens'].keys(): accounts_db[account]['tokens'][k] = v text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>' if settings.tokens_notifications == 'true': notification(text) log(f'{account} new token deposit to your wallet: {k}: {v}') _u.update_timer(k, round(v, 5)) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) else: for k1, v1 in tokens.items(): if v1 != accounts_db[account]['tokens'][k1]: if v1 > accounts_db[account]['tokens'][k1]: log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]") _u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5)) text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>" if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM': notification( f"<b>Account: {account}\n"\ f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\ f"Seems like account was banned...</b>" ) accounts_db[account]['tokens'][k1] = v1 else: log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]") text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>" accounts_db[account]['tokens'][k1] = v1 if settings.tokens_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) # check assets if assets != accounts_db[account]['assets']: # add or delete assets new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']] del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets] if new_assets: text = f"<b>Account: <code>{account}</code></b>\n" _price_sum = 0 for ass in new_assets: parsed = _u.fetch_asset(ass) if not parsed['success']: continue price = _u.get_price(parsed['template_id'], parsed['name']) log(f"{account} new asset: {ass} {parsed['name']} ({price} WAX)") text += f"<b>[{ass}] {parsed['name']} - {price} WAX</b>\n" _price_sum += price text += f"\n<b>+{round(_price_sum, 2)} WAX</b>" if settings.nfts_notifications == 'true': notification(text) elif del_assets: text = f"<b>Account: <code>{account}</code></b>\n" + '\n'.join(del_assets) log(f"{account} transfer NFTs: {' '.join(del_assets)}") if settings.nfts_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], assets=list(assets)) # check account resourses for _res in resourses.keys(): if 'stake' in _res: continue if resourses[_res] > int(settings.get(_res+'_limit')): limits_notifications, is_time_res = _u.is_time_to_notif(limits_notifications, _res, account, settings['out_of_limit_timeout']) if is_time_res: notification(f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>") log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%).") if settings.timeout: time.sleep(int(settings.timeout)) else: time.sleep(10) # start thread def start(settings, limits_notifications): while True: try: parser(settings, limits_notifications) except Exception as e: _log.exception("MainError: ") if __name__ == '__main__': Thread(target=start, args=(settings, limits_notifications,)).start() hundlers = telegramHundlers(dp, zalupa, send_reply, _u, base, executor, settings_path, accounts_path) hundlers.register_all_methods() hundlers.run() # кто прочитал тот сдохнет :)
c def send_t
identifier_name
main.py
try: from packages.telegram_hundlers import telegramHundlers from aiogram import Bot, Dispatcher, executor import asyncio from threading import Thread import time from copy import deepcopy from cfscrape import create_scraper import os from packages.load_data import loadInStrings, loadInTxt, Struct, load_settings from packages.logger import log_handler, logger from packages.data import URL as _URL from packages.data import Payload as _Payload from packages.mw_sql import baseUniversal from packages._utils import _utils from packages.telegram_hundlers import telegramHundlers except ImportError as e: print(f"ImportError: {e}") print("RU: Установите библиотеки и попробуйте снова.") print("**Запустите файл install_packages.bat в папке install чтобы автоматически установить библиотеки") print("EN: Please install packages and try again.") print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.") input() quit() banner = """ _______________________________________________________________________ | | | __ ___ __ __ ____ | | \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ | | \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| | | \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | | | \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| | | | | _ _ _ _ | | | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ | | | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ | | | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ | | |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| | | |___/ | |_______________________________________________________________________| """ print(banner) # message limit (must be lower then 4096) message_limit = 2048 # path settings_path = os.path.realpath('.') + '/settings.txt' accounts_path = os.path.realpath('.') + '/db/accounts.txt' db_path = os.path.realpath('.') + '/db/accounts.db' log_path = os.path.realpath('.') + '/parser.log' timer_path = os.path.realpath('.') + '/db/timer.json' # scraper = create_scraper() _log = logger(name='WAXParser', file=log_path, level='INFO').get_logger() log = log_handler(_log).log base = baseUniversal(db_path) # settings and other data URL = _URL() Payload = _Payload() limits_notifications = deepcopy(Payload.limits_notifications) settings = loadInTxt().get(settings_path) settings = Struct(**settings) _u = _utils(settings, base, _log, log, scraper, URL, Payload) # validate settings if not settings.bot_token or\ not settings.user_id: log('Fill bot_token and user_id in settings.txt and restart') input() quit() # telegram bot = Bot(token=settings.bot_token) dp = Dispatcher(bot) zalupa = asyncio.new_event_loop() def notification(text): asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa) async def send_to_all_ids(text): uzs = _u.get_user_ids() for u in uzs: try: await send_reply(text, u)
if not text: text = 'Empty message' if len(text) > message_limit: for x in _u.split_text(text, message_limit): await bot.send_message(user_id, x, parse_mode='html', disable_web_page_preview=True) else: await bot.send_message(user_id, text, parse_mode='html', disable_web_page_preview=True) except Exception as e: _log.exception(f'send_reply error: {repr(e)}') def parser(settings, limits_notifications): notification( f"<b>WAXParser started.\n" f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n" f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n" f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n" f"Tokens_notifications: {settings.tokens_notifications}\n" f"NFTs_notifications: {settings.nfts_notifications}</b>" ) while True: accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path) accounts_db = _u.get_accounts(whitelist=accounts) for account in accounts: acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path) if account not in acs: continue log('fetching...', account) settings = loadInTxt().get(settings_path) settings = Struct(**settings) if account not in accounts_db.keys(): accounts_db[account] = deepcopy(Payload.defoult_account_data) base.add( table='accounts', name=account, assets=[], tokens=accounts_db[account]['tokens'] ) tokens_last = accounts_db[account]['tokens'] err, tokens = _u.get_tokens(scraper, account, tokens_last) if err: _log.error(err) nfts_last = accounts_db[account]['assets'] err, assets = _u.get_nfts(scraper, account, nfts_last) if err: _log.error(err) resourses = _u.get_resourses(account) #print(resourses) if resourses['cpu_staked'] is not None: tokens['CPU_STAKED'] = resourses['cpu_staked'] else: if 'cpu_staked' in accounts_db[account]['tokens'].keys(): tokens['CPU_STAKED'] = accounts_db[account]['tokens']['cpu_staked'] # check tokens if tokens != accounts_db[account]['tokens']: # add new token or balance changed for k, v in tokens.items(): if k not in accounts_db[account]['tokens'].keys(): accounts_db[account]['tokens'][k] = v text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>' if settings.tokens_notifications == 'true': notification(text) log(f'{account} new token deposit to your wallet: {k}: {v}') _u.update_timer(k, round(v, 5)) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) else: for k1, v1 in tokens.items(): if v1 != accounts_db[account]['tokens'][k1]: if v1 > accounts_db[account]['tokens'][k1]: log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]") _u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5)) text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>" if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM': notification( f"<b>Account: {account}\n"\ f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\ f"Seems like account was banned...</b>" ) accounts_db[account]['tokens'][k1] = v1 else: log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]") text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>" accounts_db[account]['tokens'][k1] = v1 if settings.tokens_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) # check assets if assets != accounts_db[account]['assets']: # add or delete assets new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']] del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets] if new_assets: text = f"<b>Account: <code>{account}</code></b>\n" _price_sum = 0 for ass in new_assets: parsed = _u.fetch_asset(ass) if not parsed['success']: continue price = _u.get_price(parsed['template_id'], parsed['name']) log(f"{account} new asset: {ass} {parsed['name']} ({price} WAX)") text += f"<b>[{ass}] {parsed['name']} - {price} WAX</b>\n" _price_sum += price text += f"\n<b>+{round(_price_sum, 2)} WAX</b>" if settings.nfts_notifications == 'true': notification(text) elif del_assets: text = f"<b>Account: <code>{account}</code></b>\n" + '\n'.join(del_assets) log(f"{account} transfer NFTs: {' '.join(del_assets)}") if settings.nfts_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], assets=list(assets)) # check account resourses for _res in resourses.keys(): if 'stake' in _res: continue if resourses[_res] > int(settings.get(_res+'_limit')): limits_notifications, is_time_res = _u.is_time_to_notif(limits_notifications, _res, account, settings['out_of_limit_timeout']) if is_time_res: notification(f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>") log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%).") if settings.timeout: time.sleep(int(settings.timeout)) else: time.sleep(10) # start thread def start(settings, limits_notifications): while True: try: parser(settings, limits_notifications) except Exception as e: _log.exception("MainError: ") if __name__ == '__main__': Thread(target=start, args=(settings, limits_notifications,)).start() hundlers = telegramHundlers(dp, zalupa, send_reply, _u, base, executor, settings_path, accounts_path) hundlers.register_all_methods() hundlers.run() # кто прочитал тот сдохнет :)
except Exception as e: print(f'send_to_all_ids error: {e}') async def send_reply(text, user_id): try: text = str(text)
identifier_body
main.py
try: from packages.telegram_hundlers import telegramHundlers from aiogram import Bot, Dispatcher, executor import asyncio from threading import Thread import time from copy import deepcopy from cfscrape import create_scraper import os from packages.load_data import loadInStrings, loadInTxt, Struct, load_settings from packages.logger import log_handler, logger from packages.data import URL as _URL from packages.data import Payload as _Payload from packages.mw_sql import baseUniversal from packages._utils import _utils from packages.telegram_hundlers import telegramHundlers except ImportError as e: print(f"ImportError: {e}") print("RU: Установите библиотеки и попробуйте снова.") print("**Запустите файл install_packages.bat в папке install чтобы автоматически установить библиотеки") print("EN: Please install packages and try again.") print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.") input() quit() banner = """ _______________________________________________________________________ | | | __ ___ __ __ ____ | | \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ | | \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| | | \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | | | \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| | | | | _ _ _ _ | | | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ | | | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ | | | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ | | |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| | | |___/ | |_______________________________________________________________________| """ print(banner) # message limit (must be lower then 4096) message_limit = 2048 # path settings_path = os.path.realpath('.') + '/settings.txt' accounts_path = os.path.realpath('.') + '/db/accounts.txt' db_path = os.path.realpath('.') + '/db/accounts.db' log_path = os.path.realpath('.') + '/parser.log' timer_path = os.path.realpath('.') + '/db/timer.json' # scraper = create_scraper() _log = logger(name='WAXParser', file=log_path, level='INFO').get_logger() log = log_handler(_log).log base = baseUniversal(db_path) # settings and other data URL = _URL() Payload = _Payload() limits_notifications = deepcopy(Payload.limits_notifications) settings = loadInTxt().get(settings_path) settings = Struct(**settings) _u = _utils(settings, base, _log, log, scraper, URL, Payload) # validate settings if not settings.bot_token or\ not settings.user_id: log('Fill bot_token and user_id in settings.txt and restart') input() quit() # telegram bot = Bot(token=settings.bot_token) dp = Dispatcher(bot) zalupa = asyncio.new_event_loop() def notification(text): asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa) async def send_to_all_ids(text): uzs = _u.get_user_ids() for u in uzs: try: await send_reply(text, u) except Exception as e: print(f'send_to_all_ids error: {e}') async def send_reply(text, user_id): try: text = str(text) if not text: text = 'Empty message' if len(text) > message_limit: for x in _u.split_text(text, message_limit): await bot.send_message(user_id, x, parse_mode='html', disable_web_page_preview=True) else: await bot.send_message(user_id, text, parse_mode='html', disable_web_page_preview=True) except Exception as e: _log.exception(f'send_reply error: {repr(e)}') def parser(settings, limits_notifications): notification( f"<b>WAXParser started.\n" f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n" f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n" f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n" f"Tokens_notifications: {settings.tokens_notifications}\n" f"NFTs_notifications: {settings.nfts_notifications}</b>" ) while True: accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path) accounts_db = _u.get_accounts(whitelist=accounts) for account in accounts: acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path) if account not in acs: continue log('fetching...', account) settings = loadInTxt().get(settings_path) settings = Struct(**settings) if account not in accounts_db.keys(): accounts_db[account] = deepcopy(Payload.defoult_account_data) base.add( table='accounts', name=account, assets=[], tokens=accounts_db[account]['tokens'] ) tokens_last = accounts_db[account]['tokens'] err, tokens = _u.get_tokens(scraper, account, tokens_last) if err: _log.error(err) nfts_last = accounts_db[account]['assets'] err, assets = _u.get_nfts(scraper, account, nfts_last) if err: _log.error(err) resourses = _u.get_resourses(account) #print(resourses) if resourses['cpu_staked'] is not None: tokens['CPU_STAKED'] = resourses['cpu_staked'] else: if 'cpu_stak
tokens['CPU_STAKED'] = accounts_db[account]['tokens']['cpu_staked'] # check tokens if tokens != accounts_db[account]['tokens']: # add new token or balance changed for k, v in tokens.items(): if k not in accounts_db[account]['tokens'].keys(): accounts_db[account]['tokens'][k] = v text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>' if settings.tokens_notifications == 'true': notification(text) log(f'{account} new token deposit to your wallet: {k}: {v}') _u.update_timer(k, round(v, 5)) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) else: for k1, v1 in tokens.items(): if v1 != accounts_db[account]['tokens'][k1]: if v1 > accounts_db[account]['tokens'][k1]: log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]") _u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5)) text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>" if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM': notification( f"<b>Account: {account}\n"\ f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\ f"Seems like account was banned...</b>" ) accounts_db[account]['tokens'][k1] = v1 else: log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]") text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>" accounts_db[account]['tokens'][k1] = v1 if settings.tokens_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens']) # check assets if assets != accounts_db[account]['assets']: # add or delete assets new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']] del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets] if new_assets: text = f"<b>Account: <code>{account}</code></b>\n" _price_sum = 0 for ass in new_assets: parsed = _u.fetch_asset(ass) if not parsed['success']: continue price = _u.get_price(parsed['template_id'], parsed['name']) log(f"{account} new asset: {ass} {parsed['name']} ({price} WAX)") text += f"<b>[{ass}] {parsed['name']} - {price} WAX</b>\n" _price_sum += price text += f"\n<b>+{round(_price_sum, 2)} WAX</b>" if settings.nfts_notifications == 'true': notification(text) elif del_assets: text = f"<b>Account: <code>{account}</code></b>\n" + '\n'.join(del_assets) log(f"{account} transfer NFTs: {' '.join(del_assets)}") if settings.nfts_notifications == 'true': notification(text) base.edit_by('accounts', ['name', account], assets=list(assets)) # check account resourses for _res in resourses.keys(): if 'stake' in _res: continue if resourses[_res] > int(settings.get(_res+'_limit')): limits_notifications, is_time_res = _u.is_time_to_notif(limits_notifications, _res, account, settings['out_of_limit_timeout']) if is_time_res: notification(f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>") log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%).") if settings.timeout: time.sleep(int(settings.timeout)) else: time.sleep(10) # start thread def start(settings, limits_notifications): while True: try: parser(settings, limits_notifications) except Exception as e: _log.exception("MainError: ") if __name__ == '__main__': Thread(target=start, args=(settings, limits_notifications,)).start() hundlers = telegramHundlers(dp, zalupa, send_reply, _u, base, executor, settings_path, accounts_path) hundlers.register_all_methods() hundlers.run() # кто прочитал тот сдохнет :)
ed' in accounts_db[account]['tokens'].keys():
conditional_block
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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. //! Codec and layout configuration similar to upstream default substrate one. use super::{CodecError as Error, NodeCodec as NodeCodecT, *}; use trie_db::node::Value; /// No extension trie with no hashed value. pub struct HashedValueNoExt; /// No extension trie which stores value above a static size /// as external node. pub struct HashedValueNoExtThreshold<const C: u32>; impl TrieLayout for HashedValueNoExt { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = None; type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } impl<const C: u32> TrieLayout for HashedValueNoExtThreshold<C> { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = Some(C); type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } /// Constants specific to encoding with external value node support. pub mod trie_constants { const FIRST_PREFIX: u8 = 0b_00 << 6; pub const NIBBLE_SIZE_BOUND: usize = u16::max_value() as usize; pub const LEAF_PREFIX_MASK: u8 = 0b_01 << 6; pub const BRANCH_WITHOUT_MASK: u8 = 0b_10 << 6; pub const BRANCH_WITH_MASK: u8 = 0b_11 << 6; pub const EMPTY_TRIE: u8 = FIRST_PREFIX | (0b_00 << 4); pub const ALT_HASHING_LEAF_PREFIX_MASK: u8 = FIRST_PREFIX | (0b_1 << 5); pub const ALT_HASHING_BRANCH_WITH_MASK: u8 = FIRST_PREFIX | (0b_01 << 4); pub const ESCAPE_COMPACT_HEADER: u8 = EMPTY_TRIE | 0b_00_01; } #[derive(Default, Clone)] pub struct NodeCodec<H>(PhantomData<H>); impl<H: Hasher> NodeCodec<H> { fn decode_plan_inner_hashed(data: &[u8]) -> Result<NodePlan, Error> { let mut input = ByteSliceInput::new(data); let header = NodeHeader::decode(&mut input)?; let contains_hash = header.contains_hash_of_value(); let branch_has_value = if let NodeHeader::Branch(has_value, _) = &header { *has_value } else { // alt_hash_branch true }; match header { NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let bitmap_range = input.take(BITMAP_LENGTH)?; let bitmap = Bitmap::decode(&data[bitmap_range])?; let value = if branch_has_value { Some(if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }) } else { None }; let mut children = [ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, ]; for i in 0..nibble_ops::NIBBLE_LENGTH { if bitmap.value_at(i) { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; let range = input.take(count)?; children[i] = Some(if count == H::LENGTH { NodeHandlePlan::Hash(range) } else { NodeHandlePlan::Inline(range) }); } } Ok(NodePlan::NibbledBranch { partial: NibbleSlicePlan::new(partial, partial_padding), value, children, }) }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let value = if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }; Ok(NodePlan::Leaf { partial: NibbleSlicePlan::new(partial, partial_padding), value, }) }, } } } impl<H> NodeCodecT for NodeCodec<H> where H: Hasher, { const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER); type Error = Error; type HashOut = H::Out; fn hashed_null_node() -> <H as Hasher>::Out { H::hash(<Self as NodeCodecT>::empty_node()) } fn decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> { Self::decode_plan_inner_hashed(data) } fn is_empty_node(data: &[u8]) -> bool { data == <Self as NodeCodecT>::empty_node() } fn empty_node() -> &'static [u8] { &[trie_constants::EMPTY_TRIE] } fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> { let contains_hash = matches!(&value, Value::Node(..)); let mut output = if contains_hash { partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueLeaf) } else { partial_from_iterator_encode(partial, number_nibble, NodeKind::Leaf) }; match value { Value::Inline(value) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Value::Node(hash) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, }
fn extension_node( _partial: impl Iterator<Item = u8>, _nbnibble: usize, _child: ChildReference<<H as Hasher>::Out>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node( _children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, _maybe_value: Option<Value>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node_nibbled( partial: impl Iterator<Item = u8>, number_nibble: usize, children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, value: Option<Value>, ) -> Vec<u8> { let contains_hash = matches!(&value, Some(Value::Node(..))); let mut output = match (&value, contains_hash) { (&None, _) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue), (_, false) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue), (_, true) => partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch), }; let bitmap_index = output.len(); let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH]; (0..BITMAP_LENGTH).for_each(|_| output.push(0)); match value { Some(Value::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Some(Value::Node(hash)) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, None => (), } Bitmap::encode( children.map(|maybe_child| match maybe_child.borrow() { Some(ChildReference::Hash(h)) => { h.as_ref().encode_to(&mut output); true }, &Some(ChildReference::Inline(inline_data, len)) => { inline_data.as_ref()[..len].encode_to(&mut output); true }, None => false, }), bitmap.as_mut(), ); output[bitmap_index..bitmap_index + BITMAP_LENGTH] .copy_from_slice(&bitmap[..BITMAP_LENGTH]); output } } // utils /// Encode and allocate node type header (type and size), and partial value. /// It uses an iterator over encoded partial bytes as input. fn partial_from_iterator_encode<I: Iterator<Item = u8>>( partial: I, nibble_count: usize, node_kind: NodeKind, ) -> Vec<u8> { let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count); let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE)); match node_kind { NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output), NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output), NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output), NodeKind::HashedValueLeaf => NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output), NodeKind::HashedValueBranch => NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output), }; output.extend(partial); output } /// A node header. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub(crate) enum NodeHeader { Null, // contains wether there is a value and nibble count Branch(bool, usize), // contains nibble count Leaf(usize), // contains nibble count. HashedValueBranch(usize), // contains nibble count. HashedValueLeaf(usize), } impl NodeHeader { fn contains_hash_of_value(&self) -> bool { match self { NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true, _ => false, } } } /// NodeHeader without content pub(crate) enum NodeKind { Leaf, BranchNoValue, BranchWithValue, HashedValueLeaf, HashedValueBranch, } impl Encode for NodeHeader { fn encode_to<T: Output + ?Sized>(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), NodeHeader::Branch(true, nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output), NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::BRANCH_WITHOUT_MASK, 2, output, ), NodeHeader::Leaf(nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output), NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4, output, ), NodeHeader::HashedValueLeaf(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3, output, ), } } } impl parity_scale_codec::EncodeLike for NodeHeader {} impl Decode for NodeHeader { fn decode<I: Input>(input: &mut I) -> Result<Self, Error> { let i = input.read_byte()?; if i == trie_constants::EMPTY_TRIE { return Ok(NodeHeader::Null) } match i & (0b11 << 6) { trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)), trie_constants::BRANCH_WITH_MASK => Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)), trie_constants::BRANCH_WITHOUT_MASK => Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)), trie_constants::EMPTY_TRIE => { if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK { Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?)) } else if i & (0b1111 << 4) == trie_constants::ALT_HASHING_BRANCH_WITH_MASK { Ok(NodeHeader::HashedValueBranch(decode_size(i, input, 4)?)) } else { // do not allow any special encoding Err("Unallowed encoding".into()) } }, _ => unreachable!(), } } } /// Returns an iterator over encoded bytes for node header and size. /// Size encoding allows unlimited, length inefficient, representation, but /// is bounded to 16 bit maximum value to avoid possible DOS. pub(crate) fn size_and_prefix_iterator( size: usize, prefix: u8, prefix_mask: usize, ) -> impl Iterator<Item = u8> { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, size); let max_value = 255u8 >> prefix_mask; let l1 = std::cmp::min(max_value as usize - 1, size); let (first_byte, mut rem) = if size == l1 { (once(prefix + l1 as u8), 0) } else { (once(prefix + max_value as u8), size - l1) }; let next_bytes = move || { if rem > 0 { if rem < 256 { let result = rem - 1; rem = 0; Some(result as u8) } else { rem = rem.saturating_sub(255); Some(255) } } else { None } }; first_byte.chain(std::iter::from_fn(next_bytes)) } /// Encodes size and prefix to a stream output (prefix on 2 first bit only). fn encode_size_and_prefix<W>(size: usize, prefix: u8, prefix_mask: usize, out: &mut W) where W: Output + ?Sized, { for b in size_and_prefix_iterator(size, prefix, prefix_mask) { out.push_byte(b) } } /// Decode size only from stream input and header byte. fn decode_size(first: u8, input: &mut impl Input, prefix_mask: usize) -> Result<usize, Error> { let max_value = 255u8 >> prefix_mask; let mut result = (first & max_value) as usize; if result < max_value as usize { return Ok(result) } result -= 1; while result <= trie_constants::NIBBLE_SIZE_BOUND { let n = input.read_byte()? as usize; if n < 255 { return Ok(result + n + 1) } result += 255; } Ok(trie_constants::NIBBLE_SIZE_BOUND) } /// Reference implementation of a `TrieStream` without extension. #[derive(Default, Clone)] pub struct ReferenceTrieStreamNoExt { /// Current node buffer. buffer: Vec<u8>, } /// Create a leaf/branch node, encoding a number of nibbles. fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator<Item = u8> + 'a { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len()); let iter_start = match kind { NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK, 2), NodeKind::BranchNoValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2), NodeKind::BranchWithValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2), NodeKind::HashedValueLeaf => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3), NodeKind::HashedValueBranch => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4), }; iter_start .chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None }) .chain(nibbles[nibbles.len() % 2..].chunks(2).map(|ch| ch[0] << 4 | ch[1])) } use trie_root::Value as TrieStreamValue; impl TrieStream for ReferenceTrieStreamNoExt { fn new() -> Self { Self { buffer: Vec::new() } } fn append_empty_data(&mut self) { self.buffer.push(trie_constants::EMPTY_TRIE); } fn append_leaf(&mut self, key: &[u8], value: TrieStreamValue) { let kind = match &value { TrieStreamValue::Inline(..) => NodeKind::Leaf, TrieStreamValue::Node(..) => NodeKind::HashedValueLeaf, }; self.buffer.extend(fuse_nibbles_node(key, kind)); match &value { TrieStreamValue::Inline(value) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, TrieStreamValue::Node(hash) => { self.buffer.extend_from_slice(hash.as_slice()); }, }; } fn begin_branch( &mut self, maybe_partial: Option<&[u8]>, maybe_value: Option<TrieStreamValue>, has_children: impl Iterator<Item = bool>, ) { if let Some(partial) = maybe_partial { let kind = match &maybe_value { None => NodeKind::BranchNoValue, Some(TrieStreamValue::Inline(..)) => NodeKind::BranchWithValue, Some(TrieStreamValue::Node(..)) => NodeKind::HashedValueBranch, }; self.buffer.extend(fuse_nibbles_node(partial, kind)); let bm = branch_node_bit_mask(has_children); self.buffer.extend([bm.0, bm.1].iter()); } else { unreachable!("trie stream codec only for no extension trie"); } match maybe_value { None => (), Some(TrieStreamValue::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, Some(TrieStreamValue::Node(hash)) => { self.buffer.extend_from_slice(hash.as_slice()); }, } } fn append_extension(&mut self, _key: &[u8]) { unreachable!("trie stream codec only for no extension trie"); } fn append_substream<H: Hasher>(&mut self, other: Self) { let data = other.out(); match data.len() { 0..=31 => data.encode_to(&mut self.buffer), _ => H::hash(&data).as_ref().encode_to(&mut self.buffer), } } fn out(self) -> Vec<u8> { self.buffer } }
output }
random_line_split
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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. //! Codec and layout configuration similar to upstream default substrate one. use super::{CodecError as Error, NodeCodec as NodeCodecT, *}; use trie_db::node::Value; /// No extension trie with no hashed value. pub struct HashedValueNoExt; /// No extension trie which stores value above a static size /// as external node. pub struct HashedValueNoExtThreshold<const C: u32>; impl TrieLayout for HashedValueNoExt { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = None; type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } impl<const C: u32> TrieLayout for HashedValueNoExtThreshold<C> { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = Some(C); type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } /// Constants specific to encoding with external value node support. pub mod trie_constants { const FIRST_PREFIX: u8 = 0b_00 << 6; pub const NIBBLE_SIZE_BOUND: usize = u16::max_value() as usize; pub const LEAF_PREFIX_MASK: u8 = 0b_01 << 6; pub const BRANCH_WITHOUT_MASK: u8 = 0b_10 << 6; pub const BRANCH_WITH_MASK: u8 = 0b_11 << 6; pub const EMPTY_TRIE: u8 = FIRST_PREFIX | (0b_00 << 4); pub const ALT_HASHING_LEAF_PREFIX_MASK: u8 = FIRST_PREFIX | (0b_1 << 5); pub const ALT_HASHING_BRANCH_WITH_MASK: u8 = FIRST_PREFIX | (0b_01 << 4); pub const ESCAPE_COMPACT_HEADER: u8 = EMPTY_TRIE | 0b_00_01; } #[derive(Default, Clone)] pub struct NodeCodec<H>(PhantomData<H>); impl<H: Hasher> NodeCodec<H> { fn decode_plan_inner_hashed(data: &[u8]) -> Result<NodePlan, Error> { let mut input = ByteSliceInput::new(data); let header = NodeHeader::decode(&mut input)?; let contains_hash = header.contains_hash_of_value(); let branch_has_value = if let NodeHeader::Branch(has_value, _) = &header { *has_value } else { // alt_hash_branch true }; match header { NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let bitmap_range = input.take(BITMAP_LENGTH)?; let bitmap = Bitmap::decode(&data[bitmap_range])?; let value = if branch_has_value { Some(if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }) } else { None }; let mut children = [ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, ]; for i in 0..nibble_ops::NIBBLE_LENGTH { if bitmap.value_at(i) { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; let range = input.take(count)?; children[i] = Some(if count == H::LENGTH { NodeHandlePlan::Hash(range) } else { NodeHandlePlan::Inline(range) }); } } Ok(NodePlan::NibbledBranch { partial: NibbleSlicePlan::new(partial, partial_padding), value, children, }) }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) =>
, } } } impl<H> NodeCodecT for NodeCodec<H> where H: Hasher, { const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER); type Error = Error; type HashOut = H::Out; fn hashed_null_node() -> <H as Hasher>::Out { H::hash(<Self as NodeCodecT>::empty_node()) } fn decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> { Self::decode_plan_inner_hashed(data) } fn is_empty_node(data: &[u8]) -> bool { data == <Self as NodeCodecT>::empty_node() } fn empty_node() -> &'static [u8] { &[trie_constants::EMPTY_TRIE] } fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> { let contains_hash = matches!(&value, Value::Node(..)); let mut output = if contains_hash { partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueLeaf) } else { partial_from_iterator_encode(partial, number_nibble, NodeKind::Leaf) }; match value { Value::Inline(value) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Value::Node(hash) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, } output } fn extension_node( _partial: impl Iterator<Item = u8>, _nbnibble: usize, _child: ChildReference<<H as Hasher>::Out>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node( _children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, _maybe_value: Option<Value>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node_nibbled( partial: impl Iterator<Item = u8>, number_nibble: usize, children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, value: Option<Value>, ) -> Vec<u8> { let contains_hash = matches!(&value, Some(Value::Node(..))); let mut output = match (&value, contains_hash) { (&None, _) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue), (_, false) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue), (_, true) => partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch), }; let bitmap_index = output.len(); let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH]; (0..BITMAP_LENGTH).for_each(|_| output.push(0)); match value { Some(Value::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Some(Value::Node(hash)) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, None => (), } Bitmap::encode( children.map(|maybe_child| match maybe_child.borrow() { Some(ChildReference::Hash(h)) => { h.as_ref().encode_to(&mut output); true }, &Some(ChildReference::Inline(inline_data, len)) => { inline_data.as_ref()[..len].encode_to(&mut output); true }, None => false, }), bitmap.as_mut(), ); output[bitmap_index..bitmap_index + BITMAP_LENGTH] .copy_from_slice(&bitmap[..BITMAP_LENGTH]); output } } // utils /// Encode and allocate node type header (type and size), and partial value. /// It uses an iterator over encoded partial bytes as input. fn partial_from_iterator_encode<I: Iterator<Item = u8>>( partial: I, nibble_count: usize, node_kind: NodeKind, ) -> Vec<u8> { let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count); let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE)); match node_kind { NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output), NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output), NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output), NodeKind::HashedValueLeaf => NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output), NodeKind::HashedValueBranch => NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output), }; output.extend(partial); output } /// A node header. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub(crate) enum NodeHeader { Null, // contains wether there is a value and nibble count Branch(bool, usize), // contains nibble count Leaf(usize), // contains nibble count. HashedValueBranch(usize), // contains nibble count. HashedValueLeaf(usize), } impl NodeHeader { fn contains_hash_of_value(&self) -> bool { match self { NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true, _ => false, } } } /// NodeHeader without content pub(crate) enum NodeKind { Leaf, BranchNoValue, BranchWithValue, HashedValueLeaf, HashedValueBranch, } impl Encode for NodeHeader { fn encode_to<T: Output + ?Sized>(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), NodeHeader::Branch(true, nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output), NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::BRANCH_WITHOUT_MASK, 2, output, ), NodeHeader::Leaf(nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output), NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4, output, ), NodeHeader::HashedValueLeaf(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3, output, ), } } } impl parity_scale_codec::EncodeLike for NodeHeader {} impl Decode for NodeHeader { fn decode<I: Input>(input: &mut I) -> Result<Self, Error> { let i = input.read_byte()?; if i == trie_constants::EMPTY_TRIE { return Ok(NodeHeader::Null) } match i & (0b11 << 6) { trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)), trie_constants::BRANCH_WITH_MASK => Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)), trie_constants::BRANCH_WITHOUT_MASK => Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)), trie_constants::EMPTY_TRIE => { if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK { Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?)) } else if i & (0b1111 << 4) == trie_constants::ALT_HASHING_BRANCH_WITH_MASK { Ok(NodeHeader::HashedValueBranch(decode_size(i, input, 4)?)) } else { // do not allow any special encoding Err("Unallowed encoding".into()) } }, _ => unreachable!(), } } } /// Returns an iterator over encoded bytes for node header and size. /// Size encoding allows unlimited, length inefficient, representation, but /// is bounded to 16 bit maximum value to avoid possible DOS. pub(crate) fn size_and_prefix_iterator( size: usize, prefix: u8, prefix_mask: usize, ) -> impl Iterator<Item = u8> { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, size); let max_value = 255u8 >> prefix_mask; let l1 = std::cmp::min(max_value as usize - 1, size); let (first_byte, mut rem) = if size == l1 { (once(prefix + l1 as u8), 0) } else { (once(prefix + max_value as u8), size - l1) }; let next_bytes = move || { if rem > 0 { if rem < 256 { let result = rem - 1; rem = 0; Some(result as u8) } else { rem = rem.saturating_sub(255); Some(255) } } else { None } }; first_byte.chain(std::iter::from_fn(next_bytes)) } /// Encodes size and prefix to a stream output (prefix on 2 first bit only). fn encode_size_and_prefix<W>(size: usize, prefix: u8, prefix_mask: usize, out: &mut W) where W: Output + ?Sized, { for b in size_and_prefix_iterator(size, prefix, prefix_mask) { out.push_byte(b) } } /// Decode size only from stream input and header byte. fn decode_size(first: u8, input: &mut impl Input, prefix_mask: usize) -> Result<usize, Error> { let max_value = 255u8 >> prefix_mask; let mut result = (first & max_value) as usize; if result < max_value as usize { return Ok(result) } result -= 1; while result <= trie_constants::NIBBLE_SIZE_BOUND { let n = input.read_byte()? as usize; if n < 255 { return Ok(result + n + 1) } result += 255; } Ok(trie_constants::NIBBLE_SIZE_BOUND) } /// Reference implementation of a `TrieStream` without extension. #[derive(Default, Clone)] pub struct ReferenceTrieStreamNoExt { /// Current node buffer. buffer: Vec<u8>, } /// Create a leaf/branch node, encoding a number of nibbles. fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator<Item = u8> + 'a { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len()); let iter_start = match kind { NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK, 2), NodeKind::BranchNoValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2), NodeKind::BranchWithValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2), NodeKind::HashedValueLeaf => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3), NodeKind::HashedValueBranch => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4), }; iter_start .chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None }) .chain(nibbles[nibbles.len() % 2..].chunks(2).map(|ch| ch[0] << 4 | ch[1])) } use trie_root::Value as TrieStreamValue; impl TrieStream for ReferenceTrieStreamNoExt { fn new() -> Self { Self { buffer: Vec::new() } } fn append_empty_data(&mut self) { self.buffer.push(trie_constants::EMPTY_TRIE); } fn append_leaf(&mut self, key: &[u8], value: TrieStreamValue) { let kind = match &value { TrieStreamValue::Inline(..) => NodeKind::Leaf, TrieStreamValue::Node(..) => NodeKind::HashedValueLeaf, }; self.buffer.extend(fuse_nibbles_node(key, kind)); match &value { TrieStreamValue::Inline(value) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, TrieStreamValue::Node(hash) => { self.buffer.extend_from_slice(hash.as_slice()); }, }; } fn begin_branch( &mut self, maybe_partial: Option<&[u8]>, maybe_value: Option<TrieStreamValue>, has_children: impl Iterator<Item = bool>, ) { if let Some(partial) = maybe_partial { let kind = match &maybe_value { None => NodeKind::BranchNoValue, Some(TrieStreamValue::Inline(..)) => NodeKind::BranchWithValue, Some(TrieStreamValue::Node(..)) => NodeKind::HashedValueBranch, }; self.buffer.extend(fuse_nibbles_node(partial, kind)); let bm = branch_node_bit_mask(has_children); self.buffer.extend([bm.0, bm.1].iter()); } else { unreachable!("trie stream codec only for no extension trie"); } match maybe_value { None => (), Some(TrieStreamValue::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, Some(TrieStreamValue::Node(hash)) => { self.buffer.extend_from_slice(hash.as_slice()); }, } } fn append_extension(&mut self, _key: &[u8]) { unreachable!("trie stream codec only for no extension trie"); } fn append_substream<H: Hasher>(&mut self, other: Self) { let data = other.out(); match data.len() { 0..=31 => data.encode_to(&mut self.buffer), _ => H::hash(&data).as_ref().encode_to(&mut self.buffer), } } fn out(self) -> Vec<u8> { self.buffer } }
{ let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let value = if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }; Ok(NodePlan::Leaf { partial: NibbleSlicePlan::new(partial, partial_padding), value, }) }
conditional_block
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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. //! Codec and layout configuration similar to upstream default substrate one. use super::{CodecError as Error, NodeCodec as NodeCodecT, *}; use trie_db::node::Value; /// No extension trie with no hashed value. pub struct HashedValueNoExt; /// No extension trie which stores value above a static size /// as external node. pub struct HashedValueNoExtThreshold<const C: u32>; impl TrieLayout for HashedValueNoExt { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = None; type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } impl<const C: u32> TrieLayout for HashedValueNoExtThreshold<C> { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = Some(C); type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } /// Constants specific to encoding with external value node support. pub mod trie_constants { const FIRST_PREFIX: u8 = 0b_00 << 6; pub const NIBBLE_SIZE_BOUND: usize = u16::max_value() as usize; pub const LEAF_PREFIX_MASK: u8 = 0b_01 << 6; pub const BRANCH_WITHOUT_MASK: u8 = 0b_10 << 6; pub const BRANCH_WITH_MASK: u8 = 0b_11 << 6; pub const EMPTY_TRIE: u8 = FIRST_PREFIX | (0b_00 << 4); pub const ALT_HASHING_LEAF_PREFIX_MASK: u8 = FIRST_PREFIX | (0b_1 << 5); pub const ALT_HASHING_BRANCH_WITH_MASK: u8 = FIRST_PREFIX | (0b_01 << 4); pub const ESCAPE_COMPACT_HEADER: u8 = EMPTY_TRIE | 0b_00_01; } #[derive(Default, Clone)] pub struct NodeCodec<H>(PhantomData<H>); impl<H: Hasher> NodeCodec<H> { fn decode_plan_inner_hashed(data: &[u8]) -> Result<NodePlan, Error> { let mut input = ByteSliceInput::new(data); let header = NodeHeader::decode(&mut input)?; let contains_hash = header.contains_hash_of_value(); let branch_has_value = if let NodeHeader::Branch(has_value, _) = &header { *has_value } else { // alt_hash_branch true }; match header { NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let bitmap_range = input.take(BITMAP_LENGTH)?; let bitmap = Bitmap::decode(&data[bitmap_range])?; let value = if branch_has_value { Some(if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }) } else { None }; let mut children = [ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, ]; for i in 0..nibble_ops::NIBBLE_LENGTH { if bitmap.value_at(i) { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; let range = input.take(count)?; children[i] = Some(if count == H::LENGTH { NodeHandlePlan::Hash(range) } else { NodeHandlePlan::Inline(range) }); } } Ok(NodePlan::NibbledBranch { partial: NibbleSlicePlan::new(partial, partial_padding), value, children, }) }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let value = if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }; Ok(NodePlan::Leaf { partial: NibbleSlicePlan::new(partial, partial_padding), value, }) }, } } } impl<H> NodeCodecT for NodeCodec<H> where H: Hasher, { const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER); type Error = Error; type HashOut = H::Out; fn hashed_null_node() -> <H as Hasher>::Out { H::hash(<Self as NodeCodecT>::empty_node()) } fn decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> { Self::decode_plan_inner_hashed(data) } fn is_empty_node(data: &[u8]) -> bool { data == <Self as NodeCodecT>::empty_node() } fn empty_node() -> &'static [u8] { &[trie_constants::EMPTY_TRIE] } fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> { let contains_hash = matches!(&value, Value::Node(..)); let mut output = if contains_hash { partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueLeaf) } else { partial_from_iterator_encode(partial, number_nibble, NodeKind::Leaf) }; match value { Value::Inline(value) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Value::Node(hash) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, } output } fn extension_node( _partial: impl Iterator<Item = u8>, _nbnibble: usize, _child: ChildReference<<H as Hasher>::Out>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node( _children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, _maybe_value: Option<Value>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node_nibbled( partial: impl Iterator<Item = u8>, number_nibble: usize, children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, value: Option<Value>, ) -> Vec<u8> { let contains_hash = matches!(&value, Some(Value::Node(..))); let mut output = match (&value, contains_hash) { (&None, _) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue), (_, false) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue), (_, true) => partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch), }; let bitmap_index = output.len(); let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH]; (0..BITMAP_LENGTH).for_each(|_| output.push(0)); match value { Some(Value::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Some(Value::Node(hash)) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, None => (), } Bitmap::encode( children.map(|maybe_child| match maybe_child.borrow() { Some(ChildReference::Hash(h)) => { h.as_ref().encode_to(&mut output); true }, &Some(ChildReference::Inline(inline_data, len)) => { inline_data.as_ref()[..len].encode_to(&mut output); true }, None => false, }), bitmap.as_mut(), ); output[bitmap_index..bitmap_index + BITMAP_LENGTH] .copy_from_slice(&bitmap[..BITMAP_LENGTH]); output } } // utils /// Encode and allocate node type header (type and size), and partial value. /// It uses an iterator over encoded partial bytes as input. fn partial_from_iterator_encode<I: Iterator<Item = u8>>( partial: I, nibble_count: usize, node_kind: NodeKind, ) -> Vec<u8> { let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count); let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE)); match node_kind { NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output), NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output), NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output), NodeKind::HashedValueLeaf => NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output), NodeKind::HashedValueBranch => NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output), }; output.extend(partial); output } /// A node header. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub(crate) enum NodeHeader { Null, // contains wether there is a value and nibble count Branch(bool, usize), // contains nibble count Leaf(usize), // contains nibble count. HashedValueBranch(usize), // contains nibble count. HashedValueLeaf(usize), } impl NodeHeader { fn contains_hash_of_value(&self) -> bool { match self { NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true, _ => false, } } } /// NodeHeader without content pub(crate) enum
{ Leaf, BranchNoValue, BranchWithValue, HashedValueLeaf, HashedValueBranch, } impl Encode for NodeHeader { fn encode_to<T: Output + ?Sized>(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), NodeHeader::Branch(true, nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output), NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::BRANCH_WITHOUT_MASK, 2, output, ), NodeHeader::Leaf(nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output), NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4, output, ), NodeHeader::HashedValueLeaf(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3, output, ), } } } impl parity_scale_codec::EncodeLike for NodeHeader {} impl Decode for NodeHeader { fn decode<I: Input>(input: &mut I) -> Result<Self, Error> { let i = input.read_byte()?; if i == trie_constants::EMPTY_TRIE { return Ok(NodeHeader::Null) } match i & (0b11 << 6) { trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)), trie_constants::BRANCH_WITH_MASK => Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)), trie_constants::BRANCH_WITHOUT_MASK => Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)), trie_constants::EMPTY_TRIE => { if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK { Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?)) } else if i & (0b1111 << 4) == trie_constants::ALT_HASHING_BRANCH_WITH_MASK { Ok(NodeHeader::HashedValueBranch(decode_size(i, input, 4)?)) } else { // do not allow any special encoding Err("Unallowed encoding".into()) } }, _ => unreachable!(), } } } /// Returns an iterator over encoded bytes for node header and size. /// Size encoding allows unlimited, length inefficient, representation, but /// is bounded to 16 bit maximum value to avoid possible DOS. pub(crate) fn size_and_prefix_iterator( size: usize, prefix: u8, prefix_mask: usize, ) -> impl Iterator<Item = u8> { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, size); let max_value = 255u8 >> prefix_mask; let l1 = std::cmp::min(max_value as usize - 1, size); let (first_byte, mut rem) = if size == l1 { (once(prefix + l1 as u8), 0) } else { (once(prefix + max_value as u8), size - l1) }; let next_bytes = move || { if rem > 0 { if rem < 256 { let result = rem - 1; rem = 0; Some(result as u8) } else { rem = rem.saturating_sub(255); Some(255) } } else { None } }; first_byte.chain(std::iter::from_fn(next_bytes)) } /// Encodes size and prefix to a stream output (prefix on 2 first bit only). fn encode_size_and_prefix<W>(size: usize, prefix: u8, prefix_mask: usize, out: &mut W) where W: Output + ?Sized, { for b in size_and_prefix_iterator(size, prefix, prefix_mask) { out.push_byte(b) } } /// Decode size only from stream input and header byte. fn decode_size(first: u8, input: &mut impl Input, prefix_mask: usize) -> Result<usize, Error> { let max_value = 255u8 >> prefix_mask; let mut result = (first & max_value) as usize; if result < max_value as usize { return Ok(result) } result -= 1; while result <= trie_constants::NIBBLE_SIZE_BOUND { let n = input.read_byte()? as usize; if n < 255 { return Ok(result + n + 1) } result += 255; } Ok(trie_constants::NIBBLE_SIZE_BOUND) } /// Reference implementation of a `TrieStream` without extension. #[derive(Default, Clone)] pub struct ReferenceTrieStreamNoExt { /// Current node buffer. buffer: Vec<u8>, } /// Create a leaf/branch node, encoding a number of nibbles. fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator<Item = u8> + 'a { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len()); let iter_start = match kind { NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK, 2), NodeKind::BranchNoValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2), NodeKind::BranchWithValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2), NodeKind::HashedValueLeaf => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3), NodeKind::HashedValueBranch => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4), }; iter_start .chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None }) .chain(nibbles[nibbles.len() % 2..].chunks(2).map(|ch| ch[0] << 4 | ch[1])) } use trie_root::Value as TrieStreamValue; impl TrieStream for ReferenceTrieStreamNoExt { fn new() -> Self { Self { buffer: Vec::new() } } fn append_empty_data(&mut self) { self.buffer.push(trie_constants::EMPTY_TRIE); } fn append_leaf(&mut self, key: &[u8], value: TrieStreamValue) { let kind = match &value { TrieStreamValue::Inline(..) => NodeKind::Leaf, TrieStreamValue::Node(..) => NodeKind::HashedValueLeaf, }; self.buffer.extend(fuse_nibbles_node(key, kind)); match &value { TrieStreamValue::Inline(value) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, TrieStreamValue::Node(hash) => { self.buffer.extend_from_slice(hash.as_slice()); }, }; } fn begin_branch( &mut self, maybe_partial: Option<&[u8]>, maybe_value: Option<TrieStreamValue>, has_children: impl Iterator<Item = bool>, ) { if let Some(partial) = maybe_partial { let kind = match &maybe_value { None => NodeKind::BranchNoValue, Some(TrieStreamValue::Inline(..)) => NodeKind::BranchWithValue, Some(TrieStreamValue::Node(..)) => NodeKind::HashedValueBranch, }; self.buffer.extend(fuse_nibbles_node(partial, kind)); let bm = branch_node_bit_mask(has_children); self.buffer.extend([bm.0, bm.1].iter()); } else { unreachable!("trie stream codec only for no extension trie"); } match maybe_value { None => (), Some(TrieStreamValue::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, Some(TrieStreamValue::Node(hash)) => { self.buffer.extend_from_slice(hash.as_slice()); }, } } fn append_extension(&mut self, _key: &[u8]) { unreachable!("trie stream codec only for no extension trie"); } fn append_substream<H: Hasher>(&mut self, other: Self) { let data = other.out(); match data.len() { 0..=31 => data.encode_to(&mut self.buffer), _ => H::hash(&data).as_ref().encode_to(&mut self.buffer), } } fn out(self) -> Vec<u8> { self.buffer } }
NodeKind
identifier_name
substrate_like.rs
// Copyright 2017, 2021 Parity Technologies // // 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. //! Codec and layout configuration similar to upstream default substrate one. use super::{CodecError as Error, NodeCodec as NodeCodecT, *}; use trie_db::node::Value; /// No extension trie with no hashed value. pub struct HashedValueNoExt; /// No extension trie which stores value above a static size /// as external node. pub struct HashedValueNoExtThreshold<const C: u32>; impl TrieLayout for HashedValueNoExt { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = None; type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } impl<const C: u32> TrieLayout for HashedValueNoExtThreshold<C> { const USE_EXTENSION: bool = false; const ALLOW_EMPTY: bool = false; const MAX_INLINE_VALUE: Option<u32> = Some(C); type Hash = RefHasher; type Codec = ReferenceNodeCodecNoExtMeta<RefHasher>; } /// Constants specific to encoding with external value node support. pub mod trie_constants { const FIRST_PREFIX: u8 = 0b_00 << 6; pub const NIBBLE_SIZE_BOUND: usize = u16::max_value() as usize; pub const LEAF_PREFIX_MASK: u8 = 0b_01 << 6; pub const BRANCH_WITHOUT_MASK: u8 = 0b_10 << 6; pub const BRANCH_WITH_MASK: u8 = 0b_11 << 6; pub const EMPTY_TRIE: u8 = FIRST_PREFIX | (0b_00 << 4); pub const ALT_HASHING_LEAF_PREFIX_MASK: u8 = FIRST_PREFIX | (0b_1 << 5); pub const ALT_HASHING_BRANCH_WITH_MASK: u8 = FIRST_PREFIX | (0b_01 << 4); pub const ESCAPE_COMPACT_HEADER: u8 = EMPTY_TRIE | 0b_00_01; } #[derive(Default, Clone)] pub struct NodeCodec<H>(PhantomData<H>); impl<H: Hasher> NodeCodec<H> { fn decode_plan_inner_hashed(data: &[u8]) -> Result<NodePlan, Error> { let mut input = ByteSliceInput::new(data); let header = NodeHeader::decode(&mut input)?; let contains_hash = header.contains_hash_of_value(); let branch_has_value = if let NodeHeader::Branch(has_value, _) = &header { *has_value } else { // alt_hash_branch true }; match header { NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let bitmap_range = input.take(BITMAP_LENGTH)?; let bitmap = Bitmap::decode(&data[bitmap_range])?; let value = if branch_has_value { Some(if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }) } else { None }; let mut children = [ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, ]; for i in 0..nibble_ops::NIBBLE_LENGTH { if bitmap.value_at(i) { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; let range = input.take(count)?; children[i] = Some(if count == H::LENGTH { NodeHandlePlan::Hash(range) } else { NodeHandlePlan::Inline(range) }); } } Ok(NodePlan::NibbledBranch { partial: NibbleSlicePlan::new(partial, partial_padding), value, children, }) }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(CodecError::from("Bad format")) } let partial = input.take( (nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) / nibble_ops::NIBBLE_PER_BYTE, )?; let partial_padding = nibble_ops::number_padding(nibble_count); let value = if contains_hash { ValuePlan::Node(input.take(H::LENGTH)?) } else { let count = <Compact<u32>>::decode(&mut input)?.0 as usize; ValuePlan::Inline(input.take(count)?) }; Ok(NodePlan::Leaf { partial: NibbleSlicePlan::new(partial, partial_padding), value, }) }, } } } impl<H> NodeCodecT for NodeCodec<H> where H: Hasher, { const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER); type Error = Error; type HashOut = H::Out; fn hashed_null_node() -> <H as Hasher>::Out { H::hash(<Self as NodeCodecT>::empty_node()) } fn decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> { Self::decode_plan_inner_hashed(data) } fn is_empty_node(data: &[u8]) -> bool { data == <Self as NodeCodecT>::empty_node() } fn empty_node() -> &'static [u8] { &[trie_constants::EMPTY_TRIE] } fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> { let contains_hash = matches!(&value, Value::Node(..)); let mut output = if contains_hash { partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueLeaf) } else { partial_from_iterator_encode(partial, number_nibble, NodeKind::Leaf) }; match value { Value::Inline(value) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Value::Node(hash) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, } output } fn extension_node( _partial: impl Iterator<Item = u8>, _nbnibble: usize, _child: ChildReference<<H as Hasher>::Out>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node( _children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, _maybe_value: Option<Value>, ) -> Vec<u8> { unreachable!("Codec without extension.") } fn branch_node_nibbled( partial: impl Iterator<Item = u8>, number_nibble: usize, children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>, value: Option<Value>, ) -> Vec<u8> { let contains_hash = matches!(&value, Some(Value::Node(..))); let mut output = match (&value, contains_hash) { (&None, _) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue), (_, false) => partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue), (_, true) => partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch), }; let bitmap_index = output.len(); let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH]; (0..BITMAP_LENGTH).for_each(|_| output.push(0)); match value { Some(Value::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut output); output.extend_from_slice(value); }, Some(Value::Node(hash)) => { debug_assert!(hash.len() == H::LENGTH); output.extend_from_slice(hash); }, None => (), } Bitmap::encode( children.map(|maybe_child| match maybe_child.borrow() { Some(ChildReference::Hash(h)) => { h.as_ref().encode_to(&mut output); true }, &Some(ChildReference::Inline(inline_data, len)) => { inline_data.as_ref()[..len].encode_to(&mut output); true }, None => false, }), bitmap.as_mut(), ); output[bitmap_index..bitmap_index + BITMAP_LENGTH] .copy_from_slice(&bitmap[..BITMAP_LENGTH]); output } } // utils /// Encode and allocate node type header (type and size), and partial value. /// It uses an iterator over encoded partial bytes as input. fn partial_from_iterator_encode<I: Iterator<Item = u8>>( partial: I, nibble_count: usize, node_kind: NodeKind, ) -> Vec<u8> { let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count); let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE)); match node_kind { NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output), NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output), NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output), NodeKind::HashedValueLeaf => NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output), NodeKind::HashedValueBranch => NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output), }; output.extend(partial); output } /// A node header. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub(crate) enum NodeHeader { Null, // contains wether there is a value and nibble count Branch(bool, usize), // contains nibble count Leaf(usize), // contains nibble count. HashedValueBranch(usize), // contains nibble count. HashedValueLeaf(usize), } impl NodeHeader { fn contains_hash_of_value(&self) -> bool { match self { NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true, _ => false, } } } /// NodeHeader without content pub(crate) enum NodeKind { Leaf, BranchNoValue, BranchWithValue, HashedValueLeaf, HashedValueBranch, } impl Encode for NodeHeader { fn encode_to<T: Output + ?Sized>(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), NodeHeader::Branch(true, nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output), NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::BRANCH_WITHOUT_MASK, 2, output, ), NodeHeader::Leaf(nibble_count) => encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output), NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4, output, ), NodeHeader::HashedValueLeaf(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3, output, ), } } } impl parity_scale_codec::EncodeLike for NodeHeader {} impl Decode for NodeHeader { fn decode<I: Input>(input: &mut I) -> Result<Self, Error> { let i = input.read_byte()?; if i == trie_constants::EMPTY_TRIE { return Ok(NodeHeader::Null) } match i & (0b11 << 6) { trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)), trie_constants::BRANCH_WITH_MASK => Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)), trie_constants::BRANCH_WITHOUT_MASK => Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)), trie_constants::EMPTY_TRIE => { if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK { Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?)) } else if i & (0b1111 << 4) == trie_constants::ALT_HASHING_BRANCH_WITH_MASK { Ok(NodeHeader::HashedValueBranch(decode_size(i, input, 4)?)) } else { // do not allow any special encoding Err("Unallowed encoding".into()) } }, _ => unreachable!(), } } } /// Returns an iterator over encoded bytes for node header and size. /// Size encoding allows unlimited, length inefficient, representation, but /// is bounded to 16 bit maximum value to avoid possible DOS. pub(crate) fn size_and_prefix_iterator( size: usize, prefix: u8, prefix_mask: usize, ) -> impl Iterator<Item = u8> { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, size); let max_value = 255u8 >> prefix_mask; let l1 = std::cmp::min(max_value as usize - 1, size); let (first_byte, mut rem) = if size == l1 { (once(prefix + l1 as u8), 0) } else { (once(prefix + max_value as u8), size - l1) }; let next_bytes = move || { if rem > 0 { if rem < 256 { let result = rem - 1; rem = 0; Some(result as u8) } else { rem = rem.saturating_sub(255); Some(255) } } else { None } }; first_byte.chain(std::iter::from_fn(next_bytes)) } /// Encodes size and prefix to a stream output (prefix on 2 first bit only). fn encode_size_and_prefix<W>(size: usize, prefix: u8, prefix_mask: usize, out: &mut W) where W: Output + ?Sized,
/// Decode size only from stream input and header byte. fn decode_size(first: u8, input: &mut impl Input, prefix_mask: usize) -> Result<usize, Error> { let max_value = 255u8 >> prefix_mask; let mut result = (first & max_value) as usize; if result < max_value as usize { return Ok(result) } result -= 1; while result <= trie_constants::NIBBLE_SIZE_BOUND { let n = input.read_byte()? as usize; if n < 255 { return Ok(result + n + 1) } result += 255; } Ok(trie_constants::NIBBLE_SIZE_BOUND) } /// Reference implementation of a `TrieStream` without extension. #[derive(Default, Clone)] pub struct ReferenceTrieStreamNoExt { /// Current node buffer. buffer: Vec<u8>, } /// Create a leaf/branch node, encoding a number of nibbles. fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator<Item = u8> + 'a { let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len()); let iter_start = match kind { NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK, 2), NodeKind::BranchNoValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2), NodeKind::BranchWithValue => size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2), NodeKind::HashedValueLeaf => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3), NodeKind::HashedValueBranch => size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4), }; iter_start .chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None }) .chain(nibbles[nibbles.len() % 2..].chunks(2).map(|ch| ch[0] << 4 | ch[1])) } use trie_root::Value as TrieStreamValue; impl TrieStream for ReferenceTrieStreamNoExt { fn new() -> Self { Self { buffer: Vec::new() } } fn append_empty_data(&mut self) { self.buffer.push(trie_constants::EMPTY_TRIE); } fn append_leaf(&mut self, key: &[u8], value: TrieStreamValue) { let kind = match &value { TrieStreamValue::Inline(..) => NodeKind::Leaf, TrieStreamValue::Node(..) => NodeKind::HashedValueLeaf, }; self.buffer.extend(fuse_nibbles_node(key, kind)); match &value { TrieStreamValue::Inline(value) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, TrieStreamValue::Node(hash) => { self.buffer.extend_from_slice(hash.as_slice()); }, }; } fn begin_branch( &mut self, maybe_partial: Option<&[u8]>, maybe_value: Option<TrieStreamValue>, has_children: impl Iterator<Item = bool>, ) { if let Some(partial) = maybe_partial { let kind = match &maybe_value { None => NodeKind::BranchNoValue, Some(TrieStreamValue::Inline(..)) => NodeKind::BranchWithValue, Some(TrieStreamValue::Node(..)) => NodeKind::HashedValueBranch, }; self.buffer.extend(fuse_nibbles_node(partial, kind)); let bm = branch_node_bit_mask(has_children); self.buffer.extend([bm.0, bm.1].iter()); } else { unreachable!("trie stream codec only for no extension trie"); } match maybe_value { None => (), Some(TrieStreamValue::Inline(value)) => { Compact(value.len() as u32).encode_to(&mut self.buffer); self.buffer.extend_from_slice(value); }, Some(TrieStreamValue::Node(hash)) => { self.buffer.extend_from_slice(hash.as_slice()); }, } } fn append_extension(&mut self, _key: &[u8]) { unreachable!("trie stream codec only for no extension trie"); } fn append_substream<H: Hasher>(&mut self, other: Self) { let data = other.out(); match data.len() { 0..=31 => data.encode_to(&mut self.buffer), _ => H::hash(&data).as_ref().encode_to(&mut self.buffer), } } fn out(self) -> Vec<u8> { self.buffer } }
{ for b in size_and_prefix_iterator(size, prefix, prefix_mask) { out.push_byte(b) } }
identifier_body
table_schema_cache.go
package ghostferry import ( sqlorig "database/sql" "fmt" sql "github.com/Shopify/ghostferry/sqlwrapper" "strings" sq "github.com/Masterminds/squirrel" "github.com/siddontang/go-mysql/schema" "github.com/sirupsen/logrus" ) var ignoredDatabases = map[string]bool{ "mysql": true, "information_schema": true, "performance_schema": true, "sys": true, } // A comparable and lightweight type that stores the schema and table name. type TableIdentifier struct { SchemaName string TableName string } func NewTableIdentifierFromSchemaTable(table *TableSchema) TableIdentifier { return TableIdentifier{ SchemaName: table.Schema, TableName: table.Name, } } type PaginationKey struct { // The sorted list of columns Columns []*schema.TableColumn // The sorted indices of the columns as they appear in the table ColumnIndices []int // Optional index of the column that we consider most indicative of // progress. Such an entry may not exist and can be set to -1 to explicitly // indicating that it does not exist. // Used only for estimating the position of a particular value within the // range of the pagination MostSignificantColumnIndex int } func (k PaginationKey) String() string { s := "PaginationKey(" for i, column := range k.Columns { if i > 0 { s += ", " } s += fmt.Sprintf("%s[%d]", column.Name, k.ColumnIndices[i]) } return s + ")" } func (k PaginationKey) IsLinearUnsignedKey() bool { // The upstream ghostferry code assumes all pagination keys are unsigned // single-column primary keys. This requirement has been lifted from most // of the code, including copy and streaming, but not from the verifiers // yet. // This property validates if those functionalities are compatible with // this pagination key if len(k.Columns) == 1 { column := k.Columns[0] // NOTE: Technically, we should also enforce column.IsUnsigned here, // but it seems that requirement was always in ghostferry but never // explicitly enforces - enforcing it now would break backwards // compatibility, so we don't. return column.Type == schema.TYPE_NUMBER } return false } // This is a wrapper on schema.Table with some custom information we need. type TableSchema struct { *schema.Table CompressedColumnsForVerification map[string]string // Map of column name => compression type IgnoredColumnsForVerification map[string]struct{} // Set of column name PaginationKey *PaginationKey rowMd5Query string } // This query returns the MD5 hash for a row on this table. This query is valid // for both the source and the target shard. // // Any compressed columns specified via CompressedColumnsForVerification are // excluded in this checksum and the raw data is returned directly. // // Any columns specified in IgnoredColumnsForVerification are excluded from the // checksum and the raw data will not be returned. // // Note that the MD5 hash should consists of at least 1 column: the paginationKey column. // This is to say that there should never be a case where the MD5 hash is // derived from an empty string. func (t *TableSchema) FingerprintQuery(schemaName, tableName string, numRows int) (string, error) { if !t.PaginationKey.IsLinearUnsignedKey() { return "", UnsupportedPaginationKeyError(t.Schema, t.Name, t.PaginationKey.String()) } columnsToSelect := make([]string, 2+len(t.CompressedColumnsForVerification)) columnsToSelect[0] = quoteField(t.PaginationKey.Columns[0].Name) columnsToSelect[1] = t.RowMd5Query() i := 2 for columnName, _ := range t.CompressedColumnsForVerification { columnsToSelect[i] = quoteField(columnName) i += 1 } return fmt.Sprintf( "SELECT %s FROM %s WHERE %s IN (%s)", strings.Join(columnsToSelect, ","), QuotedTableNameFromString(schemaName, tableName), columnsToSelect[0], strings.Repeat("?,", numRows-1)+"?", ), nil } func (t *TableSchema) RowMd5Query() string { if t.rowMd5Query != "" { return t.rowMd5Query } columns := make([]schema.TableColumn, 0, len(t.Columns)) for _, column := range t.Columns { _, isCompressed := t.CompressedColumnsForVerification[column.Name] _, isIgnored := t.IgnoredColumnsForVerification[column.Name] if isCompressed || isIgnored { continue } columns = append(columns, column) } hashStrs := make([]string, len(columns)) for i, column := range columns { // Magic string that's unlikely to be a real record. For a history of this // issue, refer to https://github.com/Shopify/ghostferry/pull/137 hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column)) } t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ",")) return t.rowMd5Query } type TableSchemaCache map[string]*TableSchema func fullTableName(schemaName, tableName string) string { return fmt.Sprintf("%s.%s", schemaName, tableName) } func QuotedDatabaseNameFromString(database string) string { return fmt.Sprintf("`%s`", database) } func QuotedTableName(table *TableSchema) string { return QuotedTableNameFromString(table.Schema, table.Name) } func QuotedTableNameFromString(database, table string) string { return fmt.Sprintf("`%s`.`%s`", database, table) } func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) { paginatedTables = make(map[*TableSchema]*PaginationKeyData) unpaginatedTables = make([]*TableSchema, 0, len(tables)) for _, table := range tables { logger := logger.WithField("table", table.String()) isEmpty, dbErr := isEmptyTable(db, table) if dbErr != nil { err = dbErr return } // NOTE: We treat empty tables just like any other non-paginated table // to make sure they are marked as completed in the state-tracker (if // they are not already) if isEmpty || table.PaginationKey == nil { logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty) unpaginatedTables = append(unpaginatedTables, table) continue } targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder) if paginationErr != nil { logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey) err = paginationErr return } if !targetPaginationKeyExists { // potential race in the setup logger.Debugf("tracking as unpaginated table (no pagination key)") unpaginatedTables = append(unpaginatedTables, table) continue } logger.Debugf("tracking as paginated table with target-pagination %s", targetPaginationKey) paginatedTables[table] = targetPaginationKey } return } func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) { logger := logrus.WithField("tag", "table_schema_cache") tableSchemaCache := make(TableSchemaCache) dbnames, err := showDatabases(db) if err != nil { logger.WithError(err).Error("failed to show databases") return tableSchemaCache, err } dbnames, err = tableFilter.ApplicableDatabases(dbnames) if err != nil { logger.WithError(err).Error("could not apply database filter") return tableSchemaCache, err } // For each database, get a list of tables from it and cache the table's schema for _, dbname := range dbnames { dbLog := logger.WithField("database", dbname) dbLog.Debug("loading tables from database") tableNames, err := showTablesFrom(db, dbname) if err != nil { dbLog.WithError(err).Error("failed to show tables") return tableSchemaCache, err } var tableSchemas []*TableSchema for _, table := range tableNames { tableLog := dbLog.WithField("table", table) tableLog.Debug("fetching table schema") tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table) if err != nil { tableLog.WithError(err).Error("cannot fetch table schema from source db") return tableSchemaCache, err } tableSchemas = append(tableSchemas, &TableSchema{ Table: tableSchema, CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table), IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table), }) } tableSchemas, err = tableFilter.ApplicableTables(tableSchemas) if err != nil { return tableSchemaCache, nil } for _, tableSchema := range tableSchemas { tableName := tableSchema.Name tableLog := dbLog.WithField("table", tableName) tableLog.Debug("caching table schema") if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) { tableLog.Debug("table is marked for full-table copy") } else { tableLog.Debug("loading table schema pagination keys") paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig) if err != nil { tableLog.WithError(err).Error("invalid table") return tableSchemaCache, err } tableLog.Debugf("using pagination key %s", paginationKey) tableSchema.PaginationKey = paginationKey } tableSchemaCache[tableSchema.String()] = tableSchema } } logger.WithField("tables", tableSchemaCache.AllTableNames()).Info("table schemas cached") return tableSchemaCache, nil } func (t *TableSchema) findColumnByName(name string) (*schema.TableColumn, int, error) { for i, column := range t.Columns { if column.Name == name { return &column, i, nil } } return nil, -1, NonExistingPaginationKeyColumnError(t.Schema, t.Name, name) } // NonExistingPaginationKeyColumnError exported to facilitate black box testing func NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table)) } // NonExistingPaginationKeyError exported to facilitate black box testing func NonExistingPaginationKeyError(schema, table string) error { return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table)) } // UnsupportedPaginationKeyError exported to facilitate black box testing func UnsupportedPaginationKeyError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table)) } func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) { var err error paginationKeyColumns := make([]*schema.TableColumn, 0) paginationKeyColumnIndices := make([]int, 0) if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found { // Use per-schema, per-table pagination key from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else if len(t.PKColumns) > 0 { // Use Primary Key // // NOTE: A primary key has to be unique, but it may contain columns that // are not needed for uniqueness. The ideal pagination key has length of // 1, so we explicitly check if a subset of keys is sufficient. // We could also do this checking for a uniqueness contstraint in the // future for i, column := range t.Columns { if column.IsAuto { paginationKeyColumns = append(paginationKeyColumns, &column) paginationKeyColumnIndices = append(paginationKeyColumnIndices, i) break } } // if we failed finding an auto-increment, build a composite key if len(paginationKeyColumns) == 0 { for _, paginationKeyIndex := range t.PKColumns { paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex]) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } } else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found { // Try fallback from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else { // No usable pagination key found err = NonExistingPaginationKeyError(t.Schema, t.Name) } if err != nil || len(paginationKeyColumns) == 0 { if err == nil { panic(fmt.Errorf("no pagination key found, but no error set either")) } return nil, err } for _, column := range paginationKeyColumns { switch column.Type { case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY: default: return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name) } } paginationKey := &PaginationKey{ Columns: paginationKeyColumns, ColumnIndices: paginationKeyColumnIndices, } return paginationKey, err } func (c TableSchemaCache) AsSlice() (tables []*TableSchema) { for _, tableSchema := range c { tables = append(tables, tableSchema) } return } func (c TableSchemaCache) AllTableNames() (tableNames []string) { for tableName, _ := range c { tableNames = append(tableNames, tableName) } return } func (c TableSchemaCache) Get(database, table string) *TableSchema { return c[fullTableName(database, table)] } // Helper to sort a given map of tables with a second list giving a priority. // If an element is present in the input and the priority lists, the item will // appear first (in the order of the priority list), all other items appear in // the order given in the input func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) { // just a fast lookup if the list contains items already contains := map[string]struct{}{} if len(priorityList) >= 0 { for _, tableName := range priorityList { // ignore tables given in the priority list that we don't know if _, found := c[tableName]; found { contains[tableName] = struct{}{} prioritzedTableNames = append(prioritzedTableNames, tableName) } } } for tableName, _ := range c { if _, found := contains[tableName]; !found { prioritzedTableNames = append(prioritzedTableNames, tableName) } } return } // Helper to sort the given map of tables based on the dependencies between // tables in terms of foreign key constraints func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) { logger := logrus.WithField("tag", "table_schema_cache") tableReferences := make(map[QualifiedTableName]TableForeignKeys) for tableName, _ := range c { t := strings.Split(tableName, ".") table := NewQualifiedTableName(t[0], t[1]) // ignore self-references, as they are not really foreign keys referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false) if dbErr != nil { logger.WithField("table", table).Error("cannot analyze database table foreign keys") err = dbErr return } logger.Debugf("found %d reference tables for %s", len(referencedTables), table) tableReferences[table] = referencedTables } // simple fix-point loop: make sure we create at least one table per // iteration and mark tables as able to create as soon as they no-longer // refer to other tables for len(tableReferences) > 0 { createdTable := false for table, referencedTables := range tableReferences { if len(referencedTables) > 0 { continue } logger.Debugf("queuing %s", table) prioritzedTableNames = append(prioritzedTableNames, table.String()) // mark any table referring to the table as potential candidates // for being created now for otherTable, otherReferencedTables := range tableReferences { if _, found := otherReferencedTables[table]; found { delete(otherReferencedTables, table) if len(otherReferencedTables) == 0 { logger.Debugf("creation of %s unblocked creation of %s", table, otherTable) } } } delete(tableReferences, table) createdTable = true } if !createdTable { tableNames := make([]QualifiedTableName, 0, len(tableReferences)) for tableName := range tableReferences { tableNames = append(tableNames, tableName) } err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames) return } } return } func showDatabases(c *sql.DB) ([]string, error) { rows, err := c.Query("show databases") if err != nil { return []string{}, err } defer rows.Close() databases := make([]string, 0) for rows.Next() { var database string err = rows.Scan(&database) if err != nil { return databases, err } if _, ignored := ignoredDatabases[database]; ignored { continue } databases = append(databases, database) } return databases, nil } func
(c *sql.DB, dbname string) ([]string, error) { rows, err := c.Query(fmt.Sprintf("show tables from %s", quoteField(dbname))) if err != nil { return []string{}, err } defer rows.Close() tables := make([]string, 0) for rows.Next() { var table string err = rows.Scan(&table) if err != nil { return tables, err } tables = append(tables, table) } return tables, nil } func targetPaginationKey(db *sql.DB, table *TableSchema, iterateInDescendingOrder bool) (*PaginationKeyData, bool, error) { columnsToSelect := []string{"*"} selectBuilder, err := DefaultBuildSelect(columnsToSelect, table, nil, 1, !iterateInDescendingOrder) if err != nil { return nil, false, err } query, args, err := selectBuilder.ToSql() if err != nil { return nil, false, err } rows, err := db.Query(query, args...) if err != nil { return nil, false, err } defer rows.Close() if !rows.Next() { return nil, false, nil } rowData, err := ScanGenericRow(rows, len(table.Columns)) if err != nil { return nil, false, err } paginationKeyData, err := NewPaginationKeyDataFromRow(rowData, table.PaginationKey) return paginationKeyData, true, err } func isEmptyTable(db *sql.DB, table *TableSchema) (bool, error) { query, args, err := sq. Select("1"). From(QuotedTableName(table)). Limit(1). ToSql() if err != nil { return false, err } var dummy uint64 err = db.QueryRow(query, args...).Scan(&dummy) if err == sqlorig.ErrNoRows { return true, nil } return false, err }
showTablesFrom
identifier_name
table_schema_cache.go
package ghostferry import ( sqlorig "database/sql" "fmt" sql "github.com/Shopify/ghostferry/sqlwrapper" "strings" sq "github.com/Masterminds/squirrel" "github.com/siddontang/go-mysql/schema" "github.com/sirupsen/logrus" ) var ignoredDatabases = map[string]bool{ "mysql": true, "information_schema": true, "performance_schema": true, "sys": true, } // A comparable and lightweight type that stores the schema and table name. type TableIdentifier struct { SchemaName string TableName string } func NewTableIdentifierFromSchemaTable(table *TableSchema) TableIdentifier { return TableIdentifier{ SchemaName: table.Schema, TableName: table.Name, } } type PaginationKey struct { // The sorted list of columns Columns []*schema.TableColumn // The sorted indices of the columns as they appear in the table ColumnIndices []int // Optional index of the column that we consider most indicative of // progress. Such an entry may not exist and can be set to -1 to explicitly // indicating that it does not exist. // Used only for estimating the position of a particular value within the // range of the pagination MostSignificantColumnIndex int } func (k PaginationKey) String() string { s := "PaginationKey(" for i, column := range k.Columns { if i > 0 { s += ", " } s += fmt.Sprintf("%s[%d]", column.Name, k.ColumnIndices[i]) } return s + ")" } func (k PaginationKey) IsLinearUnsignedKey() bool { // The upstream ghostferry code assumes all pagination keys are unsigned // single-column primary keys. This requirement has been lifted from most // of the code, including copy and streaming, but not from the verifiers // yet. // This property validates if those functionalities are compatible with // this pagination key if len(k.Columns) == 1 { column := k.Columns[0] // NOTE: Technically, we should also enforce column.IsUnsigned here, // but it seems that requirement was always in ghostferry but never // explicitly enforces - enforcing it now would break backwards // compatibility, so we don't. return column.Type == schema.TYPE_NUMBER } return false } // This is a wrapper on schema.Table with some custom information we need. type TableSchema struct { *schema.Table CompressedColumnsForVerification map[string]string // Map of column name => compression type IgnoredColumnsForVerification map[string]struct{} // Set of column name PaginationKey *PaginationKey rowMd5Query string } // This query returns the MD5 hash for a row on this table. This query is valid // for both the source and the target shard. // // Any compressed columns specified via CompressedColumnsForVerification are // excluded in this checksum and the raw data is returned directly. // // Any columns specified in IgnoredColumnsForVerification are excluded from the // checksum and the raw data will not be returned. // // Note that the MD5 hash should consists of at least 1 column: the paginationKey column. // This is to say that there should never be a case where the MD5 hash is // derived from an empty string. func (t *TableSchema) FingerprintQuery(schemaName, tableName string, numRows int) (string, error) { if !t.PaginationKey.IsLinearUnsignedKey() { return "", UnsupportedPaginationKeyError(t.Schema, t.Name, t.PaginationKey.String()) } columnsToSelect := make([]string, 2+len(t.CompressedColumnsForVerification)) columnsToSelect[0] = quoteField(t.PaginationKey.Columns[0].Name) columnsToSelect[1] = t.RowMd5Query() i := 2 for columnName, _ := range t.CompressedColumnsForVerification { columnsToSelect[i] = quoteField(columnName) i += 1 } return fmt.Sprintf( "SELECT %s FROM %s WHERE %s IN (%s)", strings.Join(columnsToSelect, ","), QuotedTableNameFromString(schemaName, tableName), columnsToSelect[0], strings.Repeat("?,", numRows-1)+"?", ), nil } func (t *TableSchema) RowMd5Query() string { if t.rowMd5Query != "" { return t.rowMd5Query } columns := make([]schema.TableColumn, 0, len(t.Columns)) for _, column := range t.Columns { _, isCompressed := t.CompressedColumnsForVerification[column.Name] _, isIgnored := t.IgnoredColumnsForVerification[column.Name] if isCompressed || isIgnored { continue } columns = append(columns, column) } hashStrs := make([]string, len(columns)) for i, column := range columns { // Magic string that's unlikely to be a real record. For a history of this // issue, refer to https://github.com/Shopify/ghostferry/pull/137 hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column)) } t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ",")) return t.rowMd5Query } type TableSchemaCache map[string]*TableSchema func fullTableName(schemaName, tableName string) string { return fmt.Sprintf("%s.%s", schemaName, tableName) } func QuotedDatabaseNameFromString(database string) string { return fmt.Sprintf("`%s`", database) } func QuotedTableName(table *TableSchema) string { return QuotedTableNameFromString(table.Schema, table.Name) } func QuotedTableNameFromString(database, table string) string { return fmt.Sprintf("`%s`.`%s`", database, table) } func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) { paginatedTables = make(map[*TableSchema]*PaginationKeyData) unpaginatedTables = make([]*TableSchema, 0, len(tables)) for _, table := range tables { logger := logger.WithField("table", table.String()) isEmpty, dbErr := isEmptyTable(db, table) if dbErr != nil { err = dbErr return } // NOTE: We treat empty tables just like any other non-paginated table // to make sure they are marked as completed in the state-tracker (if // they are not already) if isEmpty || table.PaginationKey == nil { logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty) unpaginatedTables = append(unpaginatedTables, table) continue } targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder) if paginationErr != nil { logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey) err = paginationErr return } if !targetPaginationKeyExists { // potential race in the setup logger.Debugf("tracking as unpaginated table (no pagination key)") unpaginatedTables = append(unpaginatedTables, table) continue } logger.Debugf("tracking as paginated table with target-pagination %s", targetPaginationKey) paginatedTables[table] = targetPaginationKey } return } func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) { logger := logrus.WithField("tag", "table_schema_cache") tableSchemaCache := make(TableSchemaCache) dbnames, err := showDatabases(db) if err != nil { logger.WithError(err).Error("failed to show databases") return tableSchemaCache, err } dbnames, err = tableFilter.ApplicableDatabases(dbnames) if err != nil { logger.WithError(err).Error("could not apply database filter") return tableSchemaCache, err } // For each database, get a list of tables from it and cache the table's schema for _, dbname := range dbnames { dbLog := logger.WithField("database", dbname) dbLog.Debug("loading tables from database") tableNames, err := showTablesFrom(db, dbname) if err != nil { dbLog.WithError(err).Error("failed to show tables") return tableSchemaCache, err } var tableSchemas []*TableSchema for _, table := range tableNames { tableLog := dbLog.WithField("table", table) tableLog.Debug("fetching table schema") tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table) if err != nil { tableLog.WithError(err).Error("cannot fetch table schema from source db") return tableSchemaCache, err } tableSchemas = append(tableSchemas, &TableSchema{ Table: tableSchema, CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table), IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table), }) } tableSchemas, err = tableFilter.ApplicableTables(tableSchemas) if err != nil { return tableSchemaCache, nil } for _, tableSchema := range tableSchemas { tableName := tableSchema.Name tableLog := dbLog.WithField("table", tableName) tableLog.Debug("caching table schema") if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) { tableLog.Debug("table is marked for full-table copy") } else { tableLog.Debug("loading table schema pagination keys") paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig) if err != nil { tableLog.WithError(err).Error("invalid table") return tableSchemaCache, err } tableLog.Debugf("using pagination key %s", paginationKey) tableSchema.PaginationKey = paginationKey } tableSchemaCache[tableSchema.String()] = tableSchema } } logger.WithField("tables", tableSchemaCache.AllTableNames()).Info("table schemas cached") return tableSchemaCache, nil } func (t *TableSchema) findColumnByName(name string) (*schema.TableColumn, int, error) { for i, column := range t.Columns { if column.Name == name { return &column, i, nil } } return nil, -1, NonExistingPaginationKeyColumnError(t.Schema, t.Name, name) } // NonExistingPaginationKeyColumnError exported to facilitate black box testing func NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table)) } // NonExistingPaginationKeyError exported to facilitate black box testing func NonExistingPaginationKeyError(schema, table string) error { return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table)) } // UnsupportedPaginationKeyError exported to facilitate black box testing func UnsupportedPaginationKeyError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table)) } func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) { var err error paginationKeyColumns := make([]*schema.TableColumn, 0) paginationKeyColumnIndices := make([]int, 0) if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found { // Use per-schema, per-table pagination key from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else if len(t.PKColumns) > 0 { // Use Primary Key // // NOTE: A primary key has to be unique, but it may contain columns that // are not needed for uniqueness. The ideal pagination key has length of // 1, so we explicitly check if a subset of keys is sufficient. // We could also do this checking for a uniqueness contstraint in the // future for i, column := range t.Columns { if column.IsAuto { paginationKeyColumns = append(paginationKeyColumns, &column) paginationKeyColumnIndices = append(paginationKeyColumnIndices, i) break } } // if we failed finding an auto-increment, build a composite key if len(paginationKeyColumns) == 0 { for _, paginationKeyIndex := range t.PKColumns { paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex]) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } } else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found { // Try fallback from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else { // No usable pagination key found err = NonExistingPaginationKeyError(t.Schema, t.Name) } if err != nil || len(paginationKeyColumns) == 0 { if err == nil { panic(fmt.Errorf("no pagination key found, but no error set either")) } return nil, err } for _, column := range paginationKeyColumns { switch column.Type { case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY: default: return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name) } } paginationKey := &PaginationKey{ Columns: paginationKeyColumns, ColumnIndices: paginationKeyColumnIndices, } return paginationKey, err } func (c TableSchemaCache) AsSlice() (tables []*TableSchema) { for _, tableSchema := range c { tables = append(tables, tableSchema) } return } func (c TableSchemaCache) AllTableNames() (tableNames []string) { for tableName, _ := range c { tableNames = append(tableNames, tableName) } return } func (c TableSchemaCache) Get(database, table string) *TableSchema { return c[fullTableName(database, table)] } // Helper to sort a given map of tables with a second list giving a priority. // If an element is present in the input and the priority lists, the item will // appear first (in the order of the priority list), all other items appear in // the order given in the input func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) { // just a fast lookup if the list contains items already contains := map[string]struct{}{} if len(priorityList) >= 0 { for _, tableName := range priorityList { // ignore tables given in the priority list that we don't know if _, found := c[tableName]; found { contains[tableName] = struct{}{} prioritzedTableNames = append(prioritzedTableNames, tableName) } } } for tableName, _ := range c { if _, found := contains[tableName]; !found { prioritzedTableNames = append(prioritzedTableNames, tableName) } } return } // Helper to sort the given map of tables based on the dependencies between // tables in terms of foreign key constraints func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) { logger := logrus.WithField("tag", "table_schema_cache") tableReferences := make(map[QualifiedTableName]TableForeignKeys) for tableName, _ := range c { t := strings.Split(tableName, ".") table := NewQualifiedTableName(t[0], t[1]) // ignore self-references, as they are not really foreign keys referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false) if dbErr != nil { logger.WithField("table", table).Error("cannot analyze database table foreign keys") err = dbErr return } logger.Debugf("found %d reference tables for %s", len(referencedTables), table) tableReferences[table] = referencedTables } // simple fix-point loop: make sure we create at least one table per // iteration and mark tables as able to create as soon as they no-longer // refer to other tables for len(tableReferences) > 0 { createdTable := false for table, referencedTables := range tableReferences { if len(referencedTables) > 0 { continue } logger.Debugf("queuing %s", table) prioritzedTableNames = append(prioritzedTableNames, table.String()) // mark any table referring to the table as potential candidates // for being created now for otherTable, otherReferencedTables := range tableReferences { if _, found := otherReferencedTables[table]; found { delete(otherReferencedTables, table) if len(otherReferencedTables) == 0 { logger.Debugf("creation of %s unblocked creation of %s", table, otherTable) } } } delete(tableReferences, table) createdTable = true } if !createdTable { tableNames := make([]QualifiedTableName, 0, len(tableReferences)) for tableName := range tableReferences { tableNames = append(tableNames, tableName) } err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames) return } } return } func showDatabases(c *sql.DB) ([]string, error) { rows, err := c.Query("show databases") if err != nil { return []string{}, err } defer rows.Close() databases := make([]string, 0) for rows.Next() { var database string err = rows.Scan(&database) if err != nil { return databases, err } if _, ignored := ignoredDatabases[database]; ignored { continue } databases = append(databases, database) } return databases, nil } func showTablesFrom(c *sql.DB, dbname string) ([]string, error) { rows, err := c.Query(fmt.Sprintf("show tables from %s", quoteField(dbname))) if err != nil { return []string{}, err } defer rows.Close() tables := make([]string, 0) for rows.Next() { var table string err = rows.Scan(&table) if err != nil
tables = append(tables, table) } return tables, nil } func targetPaginationKey(db *sql.DB, table *TableSchema, iterateInDescendingOrder bool) (*PaginationKeyData, bool, error) { columnsToSelect := []string{"*"} selectBuilder, err := DefaultBuildSelect(columnsToSelect, table, nil, 1, !iterateInDescendingOrder) if err != nil { return nil, false, err } query, args, err := selectBuilder.ToSql() if err != nil { return nil, false, err } rows, err := db.Query(query, args...) if err != nil { return nil, false, err } defer rows.Close() if !rows.Next() { return nil, false, nil } rowData, err := ScanGenericRow(rows, len(table.Columns)) if err != nil { return nil, false, err } paginationKeyData, err := NewPaginationKeyDataFromRow(rowData, table.PaginationKey) return paginationKeyData, true, err } func isEmptyTable(db *sql.DB, table *TableSchema) (bool, error) { query, args, err := sq. Select("1"). From(QuotedTableName(table)). Limit(1). ToSql() if err != nil { return false, err } var dummy uint64 err = db.QueryRow(query, args...).Scan(&dummy) if err == sqlorig.ErrNoRows { return true, nil } return false, err }
{ return tables, err }
conditional_block
table_schema_cache.go
package ghostferry import ( sqlorig "database/sql" "fmt" sql "github.com/Shopify/ghostferry/sqlwrapper" "strings" sq "github.com/Masterminds/squirrel" "github.com/siddontang/go-mysql/schema" "github.com/sirupsen/logrus" ) var ignoredDatabases = map[string]bool{ "mysql": true, "information_schema": true, "performance_schema": true, "sys": true, } // A comparable and lightweight type that stores the schema and table name. type TableIdentifier struct { SchemaName string TableName string } func NewTableIdentifierFromSchemaTable(table *TableSchema) TableIdentifier { return TableIdentifier{ SchemaName: table.Schema, TableName: table.Name, } } type PaginationKey struct { // The sorted list of columns Columns []*schema.TableColumn // The sorted indices of the columns as they appear in the table ColumnIndices []int // Optional index of the column that we consider most indicative of // progress. Such an entry may not exist and can be set to -1 to explicitly // indicating that it does not exist. // Used only for estimating the position of a particular value within the // range of the pagination MostSignificantColumnIndex int } func (k PaginationKey) String() string { s := "PaginationKey(" for i, column := range k.Columns { if i > 0 { s += ", " } s += fmt.Sprintf("%s[%d]", column.Name, k.ColumnIndices[i]) } return s + ")" } func (k PaginationKey) IsLinearUnsignedKey() bool { // The upstream ghostferry code assumes all pagination keys are unsigned // single-column primary keys. This requirement has been lifted from most // of the code, including copy and streaming, but not from the verifiers // yet. // This property validates if those functionalities are compatible with // this pagination key if len(k.Columns) == 1 { column := k.Columns[0] // NOTE: Technically, we should also enforce column.IsUnsigned here, // but it seems that requirement was always in ghostferry but never // explicitly enforces - enforcing it now would break backwards // compatibility, so we don't. return column.Type == schema.TYPE_NUMBER } return false } // This is a wrapper on schema.Table with some custom information we need. type TableSchema struct { *schema.Table CompressedColumnsForVerification map[string]string // Map of column name => compression type IgnoredColumnsForVerification map[string]struct{} // Set of column name PaginationKey *PaginationKey rowMd5Query string } // This query returns the MD5 hash for a row on this table. This query is valid // for both the source and the target shard. // // Any compressed columns specified via CompressedColumnsForVerification are // excluded in this checksum and the raw data is returned directly. // // Any columns specified in IgnoredColumnsForVerification are excluded from the // checksum and the raw data will not be returned. // // Note that the MD5 hash should consists of at least 1 column: the paginationKey column. // This is to say that there should never be a case where the MD5 hash is // derived from an empty string. func (t *TableSchema) FingerprintQuery(schemaName, tableName string, numRows int) (string, error) { if !t.PaginationKey.IsLinearUnsignedKey() { return "", UnsupportedPaginationKeyError(t.Schema, t.Name, t.PaginationKey.String()) } columnsToSelect := make([]string, 2+len(t.CompressedColumnsForVerification)) columnsToSelect[0] = quoteField(t.PaginationKey.Columns[0].Name) columnsToSelect[1] = t.RowMd5Query() i := 2 for columnName, _ := range t.CompressedColumnsForVerification { columnsToSelect[i] = quoteField(columnName) i += 1 } return fmt.Sprintf( "SELECT %s FROM %s WHERE %s IN (%s)", strings.Join(columnsToSelect, ","), QuotedTableNameFromString(schemaName, tableName), columnsToSelect[0], strings.Repeat("?,", numRows-1)+"?", ), nil } func (t *TableSchema) RowMd5Query() string { if t.rowMd5Query != "" { return t.rowMd5Query } columns := make([]schema.TableColumn, 0, len(t.Columns)) for _, column := range t.Columns { _, isCompressed := t.CompressedColumnsForVerification[column.Name] _, isIgnored := t.IgnoredColumnsForVerification[column.Name] if isCompressed || isIgnored { continue } columns = append(columns, column) } hashStrs := make([]string, len(columns)) for i, column := range columns { // Magic string that's unlikely to be a real record. For a history of this // issue, refer to https://github.com/Shopify/ghostferry/pull/137 hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column)) } t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ",")) return t.rowMd5Query } type TableSchemaCache map[string]*TableSchema func fullTableName(schemaName, tableName string) string { return fmt.Sprintf("%s.%s", schemaName, tableName) } func QuotedDatabaseNameFromString(database string) string { return fmt.Sprintf("`%s`", database) } func QuotedTableName(table *TableSchema) string { return QuotedTableNameFromString(table.Schema, table.Name) } func QuotedTableNameFromString(database, table string) string { return fmt.Sprintf("`%s`.`%s`", database, table) } func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) { paginatedTables = make(map[*TableSchema]*PaginationKeyData) unpaginatedTables = make([]*TableSchema, 0, len(tables)) for _, table := range tables { logger := logger.WithField("table", table.String()) isEmpty, dbErr := isEmptyTable(db, table) if dbErr != nil { err = dbErr return } // NOTE: We treat empty tables just like any other non-paginated table // to make sure they are marked as completed in the state-tracker (if // they are not already) if isEmpty || table.PaginationKey == nil { logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty) unpaginatedTables = append(unpaginatedTables, table) continue } targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder) if paginationErr != nil { logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey) err = paginationErr return
if !targetPaginationKeyExists { // potential race in the setup logger.Debugf("tracking as unpaginated table (no pagination key)") unpaginatedTables = append(unpaginatedTables, table) continue } logger.Debugf("tracking as paginated table with target-pagination %s", targetPaginationKey) paginatedTables[table] = targetPaginationKey } return } func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) { logger := logrus.WithField("tag", "table_schema_cache") tableSchemaCache := make(TableSchemaCache) dbnames, err := showDatabases(db) if err != nil { logger.WithError(err).Error("failed to show databases") return tableSchemaCache, err } dbnames, err = tableFilter.ApplicableDatabases(dbnames) if err != nil { logger.WithError(err).Error("could not apply database filter") return tableSchemaCache, err } // For each database, get a list of tables from it and cache the table's schema for _, dbname := range dbnames { dbLog := logger.WithField("database", dbname) dbLog.Debug("loading tables from database") tableNames, err := showTablesFrom(db, dbname) if err != nil { dbLog.WithError(err).Error("failed to show tables") return tableSchemaCache, err } var tableSchemas []*TableSchema for _, table := range tableNames { tableLog := dbLog.WithField("table", table) tableLog.Debug("fetching table schema") tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table) if err != nil { tableLog.WithError(err).Error("cannot fetch table schema from source db") return tableSchemaCache, err } tableSchemas = append(tableSchemas, &TableSchema{ Table: tableSchema, CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table), IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table), }) } tableSchemas, err = tableFilter.ApplicableTables(tableSchemas) if err != nil { return tableSchemaCache, nil } for _, tableSchema := range tableSchemas { tableName := tableSchema.Name tableLog := dbLog.WithField("table", tableName) tableLog.Debug("caching table schema") if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) { tableLog.Debug("table is marked for full-table copy") } else { tableLog.Debug("loading table schema pagination keys") paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig) if err != nil { tableLog.WithError(err).Error("invalid table") return tableSchemaCache, err } tableLog.Debugf("using pagination key %s", paginationKey) tableSchema.PaginationKey = paginationKey } tableSchemaCache[tableSchema.String()] = tableSchema } } logger.WithField("tables", tableSchemaCache.AllTableNames()).Info("table schemas cached") return tableSchemaCache, nil } func (t *TableSchema) findColumnByName(name string) (*schema.TableColumn, int, error) { for i, column := range t.Columns { if column.Name == name { return &column, i, nil } } return nil, -1, NonExistingPaginationKeyColumnError(t.Schema, t.Name, name) } // NonExistingPaginationKeyColumnError exported to facilitate black box testing func NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table)) } // NonExistingPaginationKeyError exported to facilitate black box testing func NonExistingPaginationKeyError(schema, table string) error { return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table)) } // UnsupportedPaginationKeyError exported to facilitate black box testing func UnsupportedPaginationKeyError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table)) } func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) { var err error paginationKeyColumns := make([]*schema.TableColumn, 0) paginationKeyColumnIndices := make([]int, 0) if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found { // Use per-schema, per-table pagination key from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else if len(t.PKColumns) > 0 { // Use Primary Key // // NOTE: A primary key has to be unique, but it may contain columns that // are not needed for uniqueness. The ideal pagination key has length of // 1, so we explicitly check if a subset of keys is sufficient. // We could also do this checking for a uniqueness contstraint in the // future for i, column := range t.Columns { if column.IsAuto { paginationKeyColumns = append(paginationKeyColumns, &column) paginationKeyColumnIndices = append(paginationKeyColumnIndices, i) break } } // if we failed finding an auto-increment, build a composite key if len(paginationKeyColumns) == 0 { for _, paginationKeyIndex := range t.PKColumns { paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex]) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } } else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found { // Try fallback from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else { // No usable pagination key found err = NonExistingPaginationKeyError(t.Schema, t.Name) } if err != nil || len(paginationKeyColumns) == 0 { if err == nil { panic(fmt.Errorf("no pagination key found, but no error set either")) } return nil, err } for _, column := range paginationKeyColumns { switch column.Type { case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY: default: return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name) } } paginationKey := &PaginationKey{ Columns: paginationKeyColumns, ColumnIndices: paginationKeyColumnIndices, } return paginationKey, err } func (c TableSchemaCache) AsSlice() (tables []*TableSchema) { for _, tableSchema := range c { tables = append(tables, tableSchema) } return } func (c TableSchemaCache) AllTableNames() (tableNames []string) { for tableName, _ := range c { tableNames = append(tableNames, tableName) } return } func (c TableSchemaCache) Get(database, table string) *TableSchema { return c[fullTableName(database, table)] } // Helper to sort a given map of tables with a second list giving a priority. // If an element is present in the input and the priority lists, the item will // appear first (in the order of the priority list), all other items appear in // the order given in the input func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) { // just a fast lookup if the list contains items already contains := map[string]struct{}{} if len(priorityList) >= 0 { for _, tableName := range priorityList { // ignore tables given in the priority list that we don't know if _, found := c[tableName]; found { contains[tableName] = struct{}{} prioritzedTableNames = append(prioritzedTableNames, tableName) } } } for tableName, _ := range c { if _, found := contains[tableName]; !found { prioritzedTableNames = append(prioritzedTableNames, tableName) } } return } // Helper to sort the given map of tables based on the dependencies between // tables in terms of foreign key constraints func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) { logger := logrus.WithField("tag", "table_schema_cache") tableReferences := make(map[QualifiedTableName]TableForeignKeys) for tableName, _ := range c { t := strings.Split(tableName, ".") table := NewQualifiedTableName(t[0], t[1]) // ignore self-references, as they are not really foreign keys referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false) if dbErr != nil { logger.WithField("table", table).Error("cannot analyze database table foreign keys") err = dbErr return } logger.Debugf("found %d reference tables for %s", len(referencedTables), table) tableReferences[table] = referencedTables } // simple fix-point loop: make sure we create at least one table per // iteration and mark tables as able to create as soon as they no-longer // refer to other tables for len(tableReferences) > 0 { createdTable := false for table, referencedTables := range tableReferences { if len(referencedTables) > 0 { continue } logger.Debugf("queuing %s", table) prioritzedTableNames = append(prioritzedTableNames, table.String()) // mark any table referring to the table as potential candidates // for being created now for otherTable, otherReferencedTables := range tableReferences { if _, found := otherReferencedTables[table]; found { delete(otherReferencedTables, table) if len(otherReferencedTables) == 0 { logger.Debugf("creation of %s unblocked creation of %s", table, otherTable) } } } delete(tableReferences, table) createdTable = true } if !createdTable { tableNames := make([]QualifiedTableName, 0, len(tableReferences)) for tableName := range tableReferences { tableNames = append(tableNames, tableName) } err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames) return } } return } func showDatabases(c *sql.DB) ([]string, error) { rows, err := c.Query("show databases") if err != nil { return []string{}, err } defer rows.Close() databases := make([]string, 0) for rows.Next() { var database string err = rows.Scan(&database) if err != nil { return databases, err } if _, ignored := ignoredDatabases[database]; ignored { continue } databases = append(databases, database) } return databases, nil } func showTablesFrom(c *sql.DB, dbname string) ([]string, error) { rows, err := c.Query(fmt.Sprintf("show tables from %s", quoteField(dbname))) if err != nil { return []string{}, err } defer rows.Close() tables := make([]string, 0) for rows.Next() { var table string err = rows.Scan(&table) if err != nil { return tables, err } tables = append(tables, table) } return tables, nil } func targetPaginationKey(db *sql.DB, table *TableSchema, iterateInDescendingOrder bool) (*PaginationKeyData, bool, error) { columnsToSelect := []string{"*"} selectBuilder, err := DefaultBuildSelect(columnsToSelect, table, nil, 1, !iterateInDescendingOrder) if err != nil { return nil, false, err } query, args, err := selectBuilder.ToSql() if err != nil { return nil, false, err } rows, err := db.Query(query, args...) if err != nil { return nil, false, err } defer rows.Close() if !rows.Next() { return nil, false, nil } rowData, err := ScanGenericRow(rows, len(table.Columns)) if err != nil { return nil, false, err } paginationKeyData, err := NewPaginationKeyDataFromRow(rowData, table.PaginationKey) return paginationKeyData, true, err } func isEmptyTable(db *sql.DB, table *TableSchema) (bool, error) { query, args, err := sq. Select("1"). From(QuotedTableName(table)). Limit(1). ToSql() if err != nil { return false, err } var dummy uint64 err = db.QueryRow(query, args...).Scan(&dummy) if err == sqlorig.ErrNoRows { return true, nil } return false, err }
}
random_line_split
table_schema_cache.go
package ghostferry import ( sqlorig "database/sql" "fmt" sql "github.com/Shopify/ghostferry/sqlwrapper" "strings" sq "github.com/Masterminds/squirrel" "github.com/siddontang/go-mysql/schema" "github.com/sirupsen/logrus" ) var ignoredDatabases = map[string]bool{ "mysql": true, "information_schema": true, "performance_schema": true, "sys": true, } // A comparable and lightweight type that stores the schema and table name. type TableIdentifier struct { SchemaName string TableName string } func NewTableIdentifierFromSchemaTable(table *TableSchema) TableIdentifier { return TableIdentifier{ SchemaName: table.Schema, TableName: table.Name, } } type PaginationKey struct { // The sorted list of columns Columns []*schema.TableColumn // The sorted indices of the columns as they appear in the table ColumnIndices []int // Optional index of the column that we consider most indicative of // progress. Such an entry may not exist and can be set to -1 to explicitly // indicating that it does not exist. // Used only for estimating the position of a particular value within the // range of the pagination MostSignificantColumnIndex int } func (k PaginationKey) String() string { s := "PaginationKey(" for i, column := range k.Columns { if i > 0 { s += ", " } s += fmt.Sprintf("%s[%d]", column.Name, k.ColumnIndices[i]) } return s + ")" } func (k PaginationKey) IsLinearUnsignedKey() bool { // The upstream ghostferry code assumes all pagination keys are unsigned // single-column primary keys. This requirement has been lifted from most // of the code, including copy and streaming, but not from the verifiers // yet. // This property validates if those functionalities are compatible with // this pagination key if len(k.Columns) == 1 { column := k.Columns[0] // NOTE: Technically, we should also enforce column.IsUnsigned here, // but it seems that requirement was always in ghostferry but never // explicitly enforces - enforcing it now would break backwards // compatibility, so we don't. return column.Type == schema.TYPE_NUMBER } return false } // This is a wrapper on schema.Table with some custom information we need. type TableSchema struct { *schema.Table CompressedColumnsForVerification map[string]string // Map of column name => compression type IgnoredColumnsForVerification map[string]struct{} // Set of column name PaginationKey *PaginationKey rowMd5Query string } // This query returns the MD5 hash for a row on this table. This query is valid // for both the source and the target shard. // // Any compressed columns specified via CompressedColumnsForVerification are // excluded in this checksum and the raw data is returned directly. // // Any columns specified in IgnoredColumnsForVerification are excluded from the // checksum and the raw data will not be returned. // // Note that the MD5 hash should consists of at least 1 column: the paginationKey column. // This is to say that there should never be a case where the MD5 hash is // derived from an empty string. func (t *TableSchema) FingerprintQuery(schemaName, tableName string, numRows int) (string, error)
func (t *TableSchema) RowMd5Query() string { if t.rowMd5Query != "" { return t.rowMd5Query } columns := make([]schema.TableColumn, 0, len(t.Columns)) for _, column := range t.Columns { _, isCompressed := t.CompressedColumnsForVerification[column.Name] _, isIgnored := t.IgnoredColumnsForVerification[column.Name] if isCompressed || isIgnored { continue } columns = append(columns, column) } hashStrs := make([]string, len(columns)) for i, column := range columns { // Magic string that's unlikely to be a real record. For a history of this // issue, refer to https://github.com/Shopify/ghostferry/pull/137 hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column)) } t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ",")) return t.rowMd5Query } type TableSchemaCache map[string]*TableSchema func fullTableName(schemaName, tableName string) string { return fmt.Sprintf("%s.%s", schemaName, tableName) } func QuotedDatabaseNameFromString(database string) string { return fmt.Sprintf("`%s`", database) } func QuotedTableName(table *TableSchema) string { return QuotedTableNameFromString(table.Schema, table.Name) } func QuotedTableNameFromString(database, table string) string { return fmt.Sprintf("`%s`.`%s`", database, table) } func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) { paginatedTables = make(map[*TableSchema]*PaginationKeyData) unpaginatedTables = make([]*TableSchema, 0, len(tables)) for _, table := range tables { logger := logger.WithField("table", table.String()) isEmpty, dbErr := isEmptyTable(db, table) if dbErr != nil { err = dbErr return } // NOTE: We treat empty tables just like any other non-paginated table // to make sure they are marked as completed in the state-tracker (if // they are not already) if isEmpty || table.PaginationKey == nil { logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty) unpaginatedTables = append(unpaginatedTables, table) continue } targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder) if paginationErr != nil { logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey) err = paginationErr return } if !targetPaginationKeyExists { // potential race in the setup logger.Debugf("tracking as unpaginated table (no pagination key)") unpaginatedTables = append(unpaginatedTables, table) continue } logger.Debugf("tracking as paginated table with target-pagination %s", targetPaginationKey) paginatedTables[table] = targetPaginationKey } return } func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) { logger := logrus.WithField("tag", "table_schema_cache") tableSchemaCache := make(TableSchemaCache) dbnames, err := showDatabases(db) if err != nil { logger.WithError(err).Error("failed to show databases") return tableSchemaCache, err } dbnames, err = tableFilter.ApplicableDatabases(dbnames) if err != nil { logger.WithError(err).Error("could not apply database filter") return tableSchemaCache, err } // For each database, get a list of tables from it and cache the table's schema for _, dbname := range dbnames { dbLog := logger.WithField("database", dbname) dbLog.Debug("loading tables from database") tableNames, err := showTablesFrom(db, dbname) if err != nil { dbLog.WithError(err).Error("failed to show tables") return tableSchemaCache, err } var tableSchemas []*TableSchema for _, table := range tableNames { tableLog := dbLog.WithField("table", table) tableLog.Debug("fetching table schema") tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table) if err != nil { tableLog.WithError(err).Error("cannot fetch table schema from source db") return tableSchemaCache, err } tableSchemas = append(tableSchemas, &TableSchema{ Table: tableSchema, CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table), IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table), }) } tableSchemas, err = tableFilter.ApplicableTables(tableSchemas) if err != nil { return tableSchemaCache, nil } for _, tableSchema := range tableSchemas { tableName := tableSchema.Name tableLog := dbLog.WithField("table", tableName) tableLog.Debug("caching table schema") if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) { tableLog.Debug("table is marked for full-table copy") } else { tableLog.Debug("loading table schema pagination keys") paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig) if err != nil { tableLog.WithError(err).Error("invalid table") return tableSchemaCache, err } tableLog.Debugf("using pagination key %s", paginationKey) tableSchema.PaginationKey = paginationKey } tableSchemaCache[tableSchema.String()] = tableSchema } } logger.WithField("tables", tableSchemaCache.AllTableNames()).Info("table schemas cached") return tableSchemaCache, nil } func (t *TableSchema) findColumnByName(name string) (*schema.TableColumn, int, error) { for i, column := range t.Columns { if column.Name == name { return &column, i, nil } } return nil, -1, NonExistingPaginationKeyColumnError(t.Schema, t.Name, name) } // NonExistingPaginationKeyColumnError exported to facilitate black box testing func NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table)) } // NonExistingPaginationKeyError exported to facilitate black box testing func NonExistingPaginationKeyError(schema, table string) error { return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table)) } // UnsupportedPaginationKeyError exported to facilitate black box testing func UnsupportedPaginationKeyError(schema, table, paginationKey string) error { return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table)) } func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) { var err error paginationKeyColumns := make([]*schema.TableColumn, 0) paginationKeyColumnIndices := make([]int, 0) if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found { // Use per-schema, per-table pagination key from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else if len(t.PKColumns) > 0 { // Use Primary Key // // NOTE: A primary key has to be unique, but it may contain columns that // are not needed for uniqueness. The ideal pagination key has length of // 1, so we explicitly check if a subset of keys is sufficient. // We could also do this checking for a uniqueness contstraint in the // future for i, column := range t.Columns { if column.IsAuto { paginationKeyColumns = append(paginationKeyColumns, &column) paginationKeyColumnIndices = append(paginationKeyColumnIndices, i) break } } // if we failed finding an auto-increment, build a composite key if len(paginationKeyColumns) == 0 { for _, paginationKeyIndex := range t.PKColumns { paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex]) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } } else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found { // Try fallback from config var paginationKeyColumn *schema.TableColumn var paginationKeyIndex int paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName) if err == nil { paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn) paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex) } } else { // No usable pagination key found err = NonExistingPaginationKeyError(t.Schema, t.Name) } if err != nil || len(paginationKeyColumns) == 0 { if err == nil { panic(fmt.Errorf("no pagination key found, but no error set either")) } return nil, err } for _, column := range paginationKeyColumns { switch column.Type { case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY: default: return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name) } } paginationKey := &PaginationKey{ Columns: paginationKeyColumns, ColumnIndices: paginationKeyColumnIndices, } return paginationKey, err } func (c TableSchemaCache) AsSlice() (tables []*TableSchema) { for _, tableSchema := range c { tables = append(tables, tableSchema) } return } func (c TableSchemaCache) AllTableNames() (tableNames []string) { for tableName, _ := range c { tableNames = append(tableNames, tableName) } return } func (c TableSchemaCache) Get(database, table string) *TableSchema { return c[fullTableName(database, table)] } // Helper to sort a given map of tables with a second list giving a priority. // If an element is present in the input and the priority lists, the item will // appear first (in the order of the priority list), all other items appear in // the order given in the input func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) { // just a fast lookup if the list contains items already contains := map[string]struct{}{} if len(priorityList) >= 0 { for _, tableName := range priorityList { // ignore tables given in the priority list that we don't know if _, found := c[tableName]; found { contains[tableName] = struct{}{} prioritzedTableNames = append(prioritzedTableNames, tableName) } } } for tableName, _ := range c { if _, found := contains[tableName]; !found { prioritzedTableNames = append(prioritzedTableNames, tableName) } } return } // Helper to sort the given map of tables based on the dependencies between // tables in terms of foreign key constraints func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) { logger := logrus.WithField("tag", "table_schema_cache") tableReferences := make(map[QualifiedTableName]TableForeignKeys) for tableName, _ := range c { t := strings.Split(tableName, ".") table := NewQualifiedTableName(t[0], t[1]) // ignore self-references, as they are not really foreign keys referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false) if dbErr != nil { logger.WithField("table", table).Error("cannot analyze database table foreign keys") err = dbErr return } logger.Debugf("found %d reference tables for %s", len(referencedTables), table) tableReferences[table] = referencedTables } // simple fix-point loop: make sure we create at least one table per // iteration and mark tables as able to create as soon as they no-longer // refer to other tables for len(tableReferences) > 0 { createdTable := false for table, referencedTables := range tableReferences { if len(referencedTables) > 0 { continue } logger.Debugf("queuing %s", table) prioritzedTableNames = append(prioritzedTableNames, table.String()) // mark any table referring to the table as potential candidates // for being created now for otherTable, otherReferencedTables := range tableReferences { if _, found := otherReferencedTables[table]; found { delete(otherReferencedTables, table) if len(otherReferencedTables) == 0 { logger.Debugf("creation of %s unblocked creation of %s", table, otherTable) } } } delete(tableReferences, table) createdTable = true } if !createdTable { tableNames := make([]QualifiedTableName, 0, len(tableReferences)) for tableName := range tableReferences { tableNames = append(tableNames, tableName) } err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames) return } } return } func showDatabases(c *sql.DB) ([]string, error) { rows, err := c.Query("show databases") if err != nil { return []string{}, err } defer rows.Close() databases := make([]string, 0) for rows.Next() { var database string err = rows.Scan(&database) if err != nil { return databases, err } if _, ignored := ignoredDatabases[database]; ignored { continue } databases = append(databases, database) } return databases, nil } func showTablesFrom(c *sql.DB, dbname string) ([]string, error) { rows, err := c.Query(fmt.Sprintf("show tables from %s", quoteField(dbname))) if err != nil { return []string{}, err } defer rows.Close() tables := make([]string, 0) for rows.Next() { var table string err = rows.Scan(&table) if err != nil { return tables, err } tables = append(tables, table) } return tables, nil } func targetPaginationKey(db *sql.DB, table *TableSchema, iterateInDescendingOrder bool) (*PaginationKeyData, bool, error) { columnsToSelect := []string{"*"} selectBuilder, err := DefaultBuildSelect(columnsToSelect, table, nil, 1, !iterateInDescendingOrder) if err != nil { return nil, false, err } query, args, err := selectBuilder.ToSql() if err != nil { return nil, false, err } rows, err := db.Query(query, args...) if err != nil { return nil, false, err } defer rows.Close() if !rows.Next() { return nil, false, nil } rowData, err := ScanGenericRow(rows, len(table.Columns)) if err != nil { return nil, false, err } paginationKeyData, err := NewPaginationKeyDataFromRow(rowData, table.PaginationKey) return paginationKeyData, true, err } func isEmptyTable(db *sql.DB, table *TableSchema) (bool, error) { query, args, err := sq. Select("1"). From(QuotedTableName(table)). Limit(1). ToSql() if err != nil { return false, err } var dummy uint64 err = db.QueryRow(query, args...).Scan(&dummy) if err == sqlorig.ErrNoRows { return true, nil } return false, err }
{ if !t.PaginationKey.IsLinearUnsignedKey() { return "", UnsupportedPaginationKeyError(t.Schema, t.Name, t.PaginationKey.String()) } columnsToSelect := make([]string, 2+len(t.CompressedColumnsForVerification)) columnsToSelect[0] = quoteField(t.PaginationKey.Columns[0].Name) columnsToSelect[1] = t.RowMd5Query() i := 2 for columnName, _ := range t.CompressedColumnsForVerification { columnsToSelect[i] = quoteField(columnName) i += 1 } return fmt.Sprintf( "SELECT %s FROM %s WHERE %s IN (%s)", strings.Join(columnsToSelect, ","), QuotedTableNameFromString(schemaName, tableName), columnsToSelect[0], strings.Repeat("?,", numRows-1)+"?", ), nil }
identifier_body
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/writes being atomic. //! * Exploit interior mutability and atomics being Sync to allow all methods (including the ones //! which are effectively mutable) to be callable on a global non-mut static. //! * Rely on `serde` to provide the actual serialization for logging the metrics. //! * Since all metrics start at 0, we implement the `Default` trait via derive for all of them, //! to avoid having to initialize everything by hand. //! //! Moreover, the value of a metric is currently NOT reset to 0 each time it's being logged. The //! current approach is to store two values (current and previous) and compute the delta between //! them each time we do a flush (i.e by serialization). There are a number of advantages //! to this approach, including: //! * We don't have to introduce an additional write (to reset the value) from the thread which //! does to actual logging, so less synchronization effort is required. //! * We don't have to worry at all that much about losing some data if logging fails for a while //! (this could be a concern, I guess). //! If if turns out this approach is not really what we want, it's pretty easy to resort to //! something else, while working behind the same interface. use std::sync::atomic::{AtomicUsize, Ordering}; use chrono; use serde::{Serialize, Serializer}; const SYSCALL_MAX: usize = 350; /// Used for defining new types of metrics that can be either incremented with an unit /// or an arbitrary amount of units. // This trait helps with writing less code. It has to be in scope (via an use directive) in order // for its methods to be available to call on structs that implement it. pub trait Metric { /// Adds `value` to the current counter. fn add(&self, value: usize); /// Increments by 1 unit the current counter. fn inc(&self) { self.add(1); } /// Returns current value of the counter. fn count(&self) -> usize; } /// Representation of a metric that is expected to be incremented from a single thread, so it /// can use simple loads and stores with no additional synchronization necessities. // Loads are currently Relaxed everywhere, because we don't do anything besides // logging the retrieved value (their outcome os not used to modify some memory location in a // potentially inconsistent manner). There's no way currently to make sure a SimpleMetric is only // incremented by a single thread, this has to be enforced via judicious use (although, every // non-vCPU related metric is associated with a particular thread, so it shouldn't be that easy // to misuse SimpleMetric fields). #[derive(Default)] pub struct SimpleMetric(AtomicUsize); impl Metric for SimpleMetric { fn add(&self, value: usize) { let ref count = self.0; count.store(count.load(Ordering::Relaxed) + value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SimpleMetric { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize(). serializer.serialize_u64(self.0.load(Ordering::Relaxed) as u64) } } /// Representation of a metric that is expected to be incremented from more than one thread, so more /// synchronization is necessary. // It's currently used for vCPU metrics. An alternative here would be // to have one instance of every metric for each thread (like a per-thread SimpleMetric), and to // aggregate them when logging. However this probably overkill unless we have a lot of vCPUs // incrementing metrics very often. Still, it's there if we ever need it :-s #[derive(Default)] // We will be keeping two values for each metric for being able to reset // counters on each metric. // 1st member - current value being updated // 2nd member - old value that gets the current value whenever metrics is flushed to disk pub struct SharedMetric(AtomicUsize, AtomicUsize); impl Metric for SharedMetric { // While the order specified for this operation is still Relaxed, the actual instruction will // be an asm "LOCK; something" and thus atomic across multiple threads, simply because of the // fetch_and_add (as opposed to "store(load() + 1)") implementation for atomics. // TODO: would a stronger ordering make a difference here? fn add(&self, value: usize) { self.0.fetch_add(value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SharedMetric { /// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the /// flushing of metrics. /// !!! Any print of the metrics will also reset them. Use with caution !!! fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize() for some reason :( let snapshot = self.0.load(Ordering::Relaxed); let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64); if res.is_ok() { self.1.store(snapshot, Ordering::Relaxed); } res } } // The following structs are used to define a certain organization for the set of metrics we // are interested in. Whenever the name of a field differs from its ideal textual representation // in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it. /// Metrics related to the internal API server. #[derive(Default, Serialize)] pub struct ApiServerMetrics { /// Measures the process's startup time in microseconds. pub process_startup_time_us: SharedMetric, /// Measures the cpu's startup time in microseconds. pub process_startup_time_cpu_us: SharedMetric, /// Number of failures on API requests triggered by internal errors. pub sync_outcome_fails: SharedMetric, /// Number of timeouts during communication with the VMM. pub sync_vmm_send_timeout_count: SharedMetric, } /// Metrics specific to GET API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct GetRequestsMetrics { /// Number of GETs for getting information on the instance. pub instance_info_count: SharedMetric, /// Number of failures when obtaining information on the current instance. pub instance_info_fails: SharedMetric, /// Number of GETs for getting status on attaching machine configuration. pub machine_cfg_count: SharedMetric, /// Number of failures during GETs for getting information on the instance. pub machine_cfg_fails: SharedMetric, } /// Metrics specific to PUT API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PutRequestsMetrics { /// Number of PUTs triggering an action on the VM. pub actions_count: SharedMetric, /// Number of failures in triggering an action on the VM. pub actions_fails: SharedMetric, /// Number of PUTs for attaching source of boot. pub boot_source_count: SharedMetric, /// Number of failures during attaching source of boot. pub boot_source_fails: SharedMetric, /// Number of PUTs triggering a block attach. pub drive_count: SharedMetric, /// Number of failures in attaching a block device. pub drive_fails: SharedMetric, /// Number of PUTs for initializing the logging system. pub logger_count: SharedMetric, /// Number of failures in initializing the logging system. pub logger_fails: SharedMetric, /// Number of PUTs for configuring the machine. pub machine_cfg_count: SharedMetric, /// Number of failures in configuring the machine. pub machine_cfg_fails: SharedMetric, /// Number of PUTs for creating a new network interface. pub network_count: SharedMetric, /// Number of failures in creating a new network interface. pub network_fails: SharedMetric, } /// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PatchRequestsMetrics { /// Number of tries to PATCH a block device. pub drive_count: SharedMetric, /// Number of failures in PATCHing a block device. pub drive_fails: SharedMetric, } /// Block Device associated metrics. #[derive(Default, Serialize)] pub struct BlockDeviceMetrics { /// Number of times when activate failed on a block device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a block device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a block device failed. pub event_fails: SharedMetric, /// Number of failures in executing a request on a block device. pub execute_fails: SharedMetric, /// Number of invalid requests received for this block device. pub invalid_reqs_count: SharedMetric, /// Number of flushes operation triggered on this block device. pub flush_count: SharedMetric, /// Number of events triggerd on the queue of this block device. pub queue_event_count: SharedMetric, /// Number of events ratelimiter-related. pub rate_limiter_event_count: SharedMetric, /// Number of update operation triggered on this block device. pub update_count: SharedMetric, /// Number of failures while doing update on this block device. pub update_fails: SharedMetric, /// Number of bytes read by this block device. pub read_count: SharedMetric, /// Number of bytes written by this block device. pub write_count: SharedMetric, } /// Metrics specific to the i8042 device. #[derive(Default, Serialize)] pub struct I8042DeviceMetrics { /// Errors triggered while using the i8042 device. pub error_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_read_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_write_count: SharedMetric, /// Bytes read by this device. pub read_count: SharedMetric, /// Number of resets done by this device. pub reset_count: SharedMetric, /// Bytes written by this device. pub write_count: SharedMetric, } /// Metrics for the logging subsystem. #[derive(Default, Serialize)] pub struct LoggerSystemMetrics { /// Number of misses on flushing metrics. pub missed_metrics_count: SharedMetric, /// Number of errors during metrics handling. pub metrics_fails: SharedMetric, /// Number of misses on logging human readable content. pub missed_log_count: SharedMetric, /// Number of errors while trying to log human readable content. pub log_fails: SharedMetric, } /// Metrics for the MMDS functionality. #[derive(Default, Serialize)] pub struct MmdsMetrics { /// Number of frames rerouted to MMDS. pub rx_accepted: SharedMetric, /// Number of errors while handling a frame through MMDS. pub rx_accepted_err: SharedMetric, /// Number of uncommon events encountered while processing packets through MMDS. pub rx_accepted_unusual: SharedMetric, /// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS. pub rx_bad_eth: SharedMetric, /// The total number of bytes sent by the MMDS. pub tx_bytes: SharedMetric, /// The number of errors raised by the MMDS while attempting to send frames/packets/segments. pub tx_errors: SharedMetric, /// The number of frames sent by the MMDS. pub tx_frames: SharedMetric, /// The number of connections successfully accepted by the MMDS TCP handler. pub connections_created: SharedMetric, /// The number of connections cleaned up by the MMDS TCP handler. pub connections_destroyed: SharedMetric, } /// Network-related metrics. #[derive(Default, Serialize)] pub struct NetDeviceMetrics { /// Number of times when activate failed on a network device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a network device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a network device failed. pub event_fails: SharedMetric, /// Number of events associated with the receiving queue. pub rx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the receiving path. pub rx_event_rate_limiter_count: SharedMetric, /// Number of events received on the associated tap. pub rx_tap_event_count: SharedMetric, /// Number of bytes received. pub rx_bytes_count: SharedMetric, /// Number of packets received. pub rx_packets_count: SharedMetric, /// Number of errors while receiving data. pub rx_fails: SharedMetric, /// Number of transmitted bytes. pub tx_bytes_count: SharedMetric, /// Number of errors while transmitting data. pub tx_fails: SharedMetric, /// Number of transmitted packets. pub tx_packets_count: SharedMetric, /// Number of events associated with the transmitting queue. pub tx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the transmitting path. pub tx_rate_limiter_event_count: SharedMetric, } /// Metrics for the seccomp filtering. #[derive(Serialize)] pub struct SeccompMetrics { /// Number of black listed syscalls. pub bad_syscalls: Vec<SharedMetric>, /// Number of errors inside the seccomp filtering. pub num_faults: SharedMetric, } impl Default for SeccompMetrics { fn default() -> SeccompMetrics { let mut def_syscalls = vec![]; for _syscall in 0..SYSCALL_MAX { def_syscalls.push(SharedMetric::default()); } SeccompMetrics { num_faults: SharedMetric::default(), bad_syscalls: def_syscalls, } } } /// Metrics specific to the UART device. #[derive(Default, Serialize)] pub struct SerialDeviceMetrics { /// Errors triggered while using the UART device. pub error_count: SharedMetric, /// Number of flush operations. pub flush_count: SharedMetric, /// Number of read calls that did not trigger a read. pub missed_read_count: SharedMetric, /// Number of write calls that did not trigger a write. pub missed_write_count: SharedMetric, /// Number of succeeded read calls. pub read_count: SharedMetric, /// Number of succeeded write calls. pub write_count: SharedMetric, } /// Metrics specific to VCPUs' mode of functioning. #[derive(Default, Serialize)] pub struct VcpuMetrics { /// Number of KVM exits for handling input IO. pub exit_io_in: SharedMetric, /// Number of KVM exits for handling output IO. pub exit_io_out: SharedMetric, /// Number of KVM exits for handling MMIO reads. pub exit_mmio_read: SharedMetric, /// Number of KVM exits for handling MMIO writes. pub exit_mmio_write: SharedMetric, /// Number of errors during this VCPU's run. pub failures: SharedMetric, /// Failures in configuring the CPUID. pub fitler_cpuid: SharedMetric, } /// Metrics specific to the machine manager as a whole. #[derive(Default, Serialize)] pub struct VmmMetrics { /// Number of device related events received for a VM. pub device_events: SharedMetric, /// Metric for signaling a panic has occurred. pub panic_count: SharedMetric, } /// Memory usage metrics. #[derive(Default, Serialize)] pub struct MemoryMetrics { /// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`. pub dirty_pages: SharedMetric, } // The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized. #[derive(Default)] struct SerializeToUtcTimestampMs; impl Serialize for SerializeToUtcTimestampMs { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>
} /// Structure storing all metrics while enforcing serialization support on them. #[derive(Default, Serialize)] pub struct FirecrackerMetrics { utc_timestamp_ms: SerializeToUtcTimestampMs, /// API Server related metrics. pub api_server: ApiServerMetrics, /// A block device's related metrics. pub block: BlockDeviceMetrics, /// Metrics related to API GET requests. pub get_api_requests: GetRequestsMetrics, /// Metrics relaetd to the i8042 device. pub i8042: I8042DeviceMetrics, /// Logging related metrics. pub logger: LoggerSystemMetrics, /// Metrics specific to MMDS functionality. pub mmds: MmdsMetrics, /// A network device's related metrics. pub net: NetDeviceMetrics, /// Metrics related to API PATCH requests. pub patch_api_requests: PatchRequestsMetrics, /// Metrics related to API PUT requests. pub put_api_requests: PutRequestsMetrics, /// Metrics related to seccomp filtering. pub seccomp: SeccompMetrics, /// Metrics related to a vcpu's functioning. pub vcpu: VcpuMetrics, /// Metrics related to the virtual machine manager. pub vmm: VmmMetrics, /// Metrics related to the UART device. pub uart: SerialDeviceMetrics, /// Memory usage metrics. pub memory: MemoryMetrics, } lazy_static! { /// Static instance used for handling metrics. /// pub static ref METRICS: FirecrackerMetrics = FirecrackerMetrics::default(); } #[cfg(test)] mod tests { extern crate serde_json; use super::*; use std::sync::Arc; use std::thread; #[test] fn test_metric() { let m1 = SimpleMetric::default(); m1.inc(); m1.inc(); m1.add(5); m1.inc(); assert_eq!(m1.count(), 8); let m2 = Arc::new(SharedMetric::default()); // We're going to create a number of threads that will attempt to increase this metric // in parallel. If everything goes fine we still can't be sure the synchronization works, // but it something fails, then we definitely have a problem :-s const NUM_THREADS_TO_SPAWN: usize = 4; const NUM_INCREMENTS_PER_THREAD: usize = 100000; const M2_INITIAL_COUNT: usize = 123; m2.add(M2_INITIAL_COUNT); let mut v = Vec::with_capacity(NUM_THREADS_TO_SPAWN); for _ in 0..NUM_THREADS_TO_SPAWN { let r = m2.clone(); v.push(thread::spawn(move || { for _ in 0..NUM_INCREMENTS_PER_THREAD { r.inc(); } })); } for handle in v { handle.join().unwrap(); } assert_eq!( m2.count(), M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD ); } #[test] fn test_serialize() { let s = serde_json::to_string(&FirecrackerMetrics::default()); assert!(s.is_ok()); } }
{ serializer.serialize_i64(chrono::Utc::now().timestamp_millis()) }
identifier_body
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/writes being atomic. //! * Exploit interior mutability and atomics being Sync to allow all methods (including the ones //! which are effectively mutable) to be callable on a global non-mut static. //! * Rely on `serde` to provide the actual serialization for logging the metrics. //! * Since all metrics start at 0, we implement the `Default` trait via derive for all of them, //! to avoid having to initialize everything by hand. //! //! Moreover, the value of a metric is currently NOT reset to 0 each time it's being logged. The //! current approach is to store two values (current and previous) and compute the delta between //! them each time we do a flush (i.e by serialization). There are a number of advantages //! to this approach, including: //! * We don't have to introduce an additional write (to reset the value) from the thread which //! does to actual logging, so less synchronization effort is required. //! * We don't have to worry at all that much about losing some data if logging fails for a while //! (this could be a concern, I guess). //! If if turns out this approach is not really what we want, it's pretty easy to resort to //! something else, while working behind the same interface. use std::sync::atomic::{AtomicUsize, Ordering}; use chrono; use serde::{Serialize, Serializer}; const SYSCALL_MAX: usize = 350; /// Used for defining new types of metrics that can be either incremented with an unit /// or an arbitrary amount of units. // This trait helps with writing less code. It has to be in scope (via an use directive) in order // for its methods to be available to call on structs that implement it. pub trait Metric { /// Adds `value` to the current counter. fn add(&self, value: usize); /// Increments by 1 unit the current counter. fn inc(&self) { self.add(1); } /// Returns current value of the counter. fn count(&self) -> usize; } /// Representation of a metric that is expected to be incremented from a single thread, so it /// can use simple loads and stores with no additional synchronization necessities. // Loads are currently Relaxed everywhere, because we don't do anything besides // logging the retrieved value (their outcome os not used to modify some memory location in a // potentially inconsistent manner). There's no way currently to make sure a SimpleMetric is only // incremented by a single thread, this has to be enforced via judicious use (although, every // non-vCPU related metric is associated with a particular thread, so it shouldn't be that easy // to misuse SimpleMetric fields). #[derive(Default)] pub struct SimpleMetric(AtomicUsize); impl Metric for SimpleMetric { fn add(&self, value: usize) { let ref count = self.0; count.store(count.load(Ordering::Relaxed) + value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SimpleMetric { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize(). serializer.serialize_u64(self.0.load(Ordering::Relaxed) as u64) } } /// Representation of a metric that is expected to be incremented from more than one thread, so more /// synchronization is necessary. // It's currently used for vCPU metrics. An alternative here would be // to have one instance of every metric for each thread (like a per-thread SimpleMetric), and to // aggregate them when logging. However this probably overkill unless we have a lot of vCPUs // incrementing metrics very often. Still, it's there if we ever need it :-s #[derive(Default)] // We will be keeping two values for each metric for being able to reset // counters on each metric. // 1st member - current value being updated // 2nd member - old value that gets the current value whenever metrics is flushed to disk pub struct SharedMetric(AtomicUsize, AtomicUsize); impl Metric for SharedMetric { // While the order specified for this operation is still Relaxed, the actual instruction will // be an asm "LOCK; something" and thus atomic across multiple threads, simply because of the // fetch_and_add (as opposed to "store(load() + 1)") implementation for atomics. // TODO: would a stronger ordering make a difference here? fn add(&self, value: usize) { self.0.fetch_add(value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SharedMetric { /// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the /// flushing of metrics. /// !!! Any print of the metrics will also reset them. Use with caution !!! fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize() for some reason :( let snapshot = self.0.load(Ordering::Relaxed); let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64); if res.is_ok() { self.1.store(snapshot, Ordering::Relaxed); } res } } // The following structs are used to define a certain organization for the set of metrics we // are interested in. Whenever the name of a field differs from its ideal textual representation // in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it. /// Metrics related to the internal API server. #[derive(Default, Serialize)] pub struct ApiServerMetrics { /// Measures the process's startup time in microseconds. pub process_startup_time_us: SharedMetric, /// Measures the cpu's startup time in microseconds. pub process_startup_time_cpu_us: SharedMetric, /// Number of failures on API requests triggered by internal errors. pub sync_outcome_fails: SharedMetric, /// Number of timeouts during communication with the VMM. pub sync_vmm_send_timeout_count: SharedMetric, } /// Metrics specific to GET API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct GetRequestsMetrics { /// Number of GETs for getting information on the instance. pub instance_info_count: SharedMetric, /// Number of failures when obtaining information on the current instance. pub instance_info_fails: SharedMetric, /// Number of GETs for getting status on attaching machine configuration. pub machine_cfg_count: SharedMetric, /// Number of failures during GETs for getting information on the instance. pub machine_cfg_fails: SharedMetric, } /// Metrics specific to PUT API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PutRequestsMetrics { /// Number of PUTs triggering an action on the VM. pub actions_count: SharedMetric, /// Number of failures in triggering an action on the VM. pub actions_fails: SharedMetric, /// Number of PUTs for attaching source of boot. pub boot_source_count: SharedMetric, /// Number of failures during attaching source of boot. pub boot_source_fails: SharedMetric, /// Number of PUTs triggering a block attach. pub drive_count: SharedMetric, /// Number of failures in attaching a block device. pub drive_fails: SharedMetric, /// Number of PUTs for initializing the logging system. pub logger_count: SharedMetric, /// Number of failures in initializing the logging system. pub logger_fails: SharedMetric, /// Number of PUTs for configuring the machine. pub machine_cfg_count: SharedMetric, /// Number of failures in configuring the machine. pub machine_cfg_fails: SharedMetric, /// Number of PUTs for creating a new network interface. pub network_count: SharedMetric, /// Number of failures in creating a new network interface. pub network_fails: SharedMetric, } /// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PatchRequestsMetrics { /// Number of tries to PATCH a block device. pub drive_count: SharedMetric, /// Number of failures in PATCHing a block device. pub drive_fails: SharedMetric, } /// Block Device associated metrics. #[derive(Default, Serialize)] pub struct BlockDeviceMetrics { /// Number of times when activate failed on a block device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a block device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a block device failed. pub event_fails: SharedMetric, /// Number of failures in executing a request on a block device. pub execute_fails: SharedMetric, /// Number of invalid requests received for this block device. pub invalid_reqs_count: SharedMetric, /// Number of flushes operation triggered on this block device. pub flush_count: SharedMetric, /// Number of events triggerd on the queue of this block device. pub queue_event_count: SharedMetric, /// Number of events ratelimiter-related. pub rate_limiter_event_count: SharedMetric, /// Number of update operation triggered on this block device. pub update_count: SharedMetric, /// Number of failures while doing update on this block device. pub update_fails: SharedMetric, /// Number of bytes read by this block device. pub read_count: SharedMetric, /// Number of bytes written by this block device. pub write_count: SharedMetric, } /// Metrics specific to the i8042 device. #[derive(Default, Serialize)] pub struct I8042DeviceMetrics { /// Errors triggered while using the i8042 device. pub error_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_read_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_write_count: SharedMetric, /// Bytes read by this device. pub read_count: SharedMetric, /// Number of resets done by this device. pub reset_count: SharedMetric, /// Bytes written by this device. pub write_count: SharedMetric, } /// Metrics for the logging subsystem. #[derive(Default, Serialize)] pub struct LoggerSystemMetrics { /// Number of misses on flushing metrics. pub missed_metrics_count: SharedMetric, /// Number of errors during metrics handling. pub metrics_fails: SharedMetric, /// Number of misses on logging human readable content. pub missed_log_count: SharedMetric, /// Number of errors while trying to log human readable content. pub log_fails: SharedMetric, } /// Metrics for the MMDS functionality. #[derive(Default, Serialize)] pub struct MmdsMetrics { /// Number of frames rerouted to MMDS. pub rx_accepted: SharedMetric, /// Number of errors while handling a frame through MMDS. pub rx_accepted_err: SharedMetric, /// Number of uncommon events encountered while processing packets through MMDS. pub rx_accepted_unusual: SharedMetric, /// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS. pub rx_bad_eth: SharedMetric, /// The total number of bytes sent by the MMDS. pub tx_bytes: SharedMetric, /// The number of errors raised by the MMDS while attempting to send frames/packets/segments. pub tx_errors: SharedMetric, /// The number of frames sent by the MMDS. pub tx_frames: SharedMetric, /// The number of connections successfully accepted by the MMDS TCP handler. pub connections_created: SharedMetric, /// The number of connections cleaned up by the MMDS TCP handler. pub connections_destroyed: SharedMetric, } /// Network-related metrics. #[derive(Default, Serialize)] pub struct NetDeviceMetrics { /// Number of times when activate failed on a network device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a network device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a network device failed. pub event_fails: SharedMetric, /// Number of events associated with the receiving queue. pub rx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the receiving path. pub rx_event_rate_limiter_count: SharedMetric, /// Number of events received on the associated tap. pub rx_tap_event_count: SharedMetric, /// Number of bytes received. pub rx_bytes_count: SharedMetric, /// Number of packets received. pub rx_packets_count: SharedMetric, /// Number of errors while receiving data. pub rx_fails: SharedMetric, /// Number of transmitted bytes. pub tx_bytes_count: SharedMetric, /// Number of errors while transmitting data. pub tx_fails: SharedMetric, /// Number of transmitted packets. pub tx_packets_count: SharedMetric, /// Number of events associated with the transmitting queue. pub tx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the transmitting path. pub tx_rate_limiter_event_count: SharedMetric, } /// Metrics for the seccomp filtering. #[derive(Serialize)] pub struct SeccompMetrics { /// Number of black listed syscalls. pub bad_syscalls: Vec<SharedMetric>, /// Number of errors inside the seccomp filtering. pub num_faults: SharedMetric, } impl Default for SeccompMetrics { fn default() -> SeccompMetrics { let mut def_syscalls = vec![]; for _syscall in 0..SYSCALL_MAX { def_syscalls.push(SharedMetric::default()); } SeccompMetrics { num_faults: SharedMetric::default(), bad_syscalls: def_syscalls, } } } /// Metrics specific to the UART device. #[derive(Default, Serialize)] pub struct SerialDeviceMetrics { /// Errors triggered while using the UART device. pub error_count: SharedMetric, /// Number of flush operations. pub flush_count: SharedMetric, /// Number of read calls that did not trigger a read. pub missed_read_count: SharedMetric, /// Number of write calls that did not trigger a write. pub missed_write_count: SharedMetric, /// Number of succeeded read calls. pub read_count: SharedMetric, /// Number of succeeded write calls. pub write_count: SharedMetric, } /// Metrics specific to VCPUs' mode of functioning. #[derive(Default, Serialize)] pub struct VcpuMetrics { /// Number of KVM exits for handling input IO. pub exit_io_in: SharedMetric, /// Number of KVM exits for handling output IO. pub exit_io_out: SharedMetric, /// Number of KVM exits for handling MMIO reads. pub exit_mmio_read: SharedMetric, /// Number of KVM exits for handling MMIO writes. pub exit_mmio_write: SharedMetric, /// Number of errors during this VCPU's run. pub failures: SharedMetric, /// Failures in configuring the CPUID. pub fitler_cpuid: SharedMetric, } /// Metrics specific to the machine manager as a whole. #[derive(Default, Serialize)] pub struct VmmMetrics { /// Number of device related events received for a VM. pub device_events: SharedMetric, /// Metric for signaling a panic has occurred. pub panic_count: SharedMetric, } /// Memory usage metrics. #[derive(Default, Serialize)] pub struct MemoryMetrics { /// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`. pub dirty_pages: SharedMetric, } // The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized. #[derive(Default)] struct SerializeToUtcTimestampMs; impl Serialize for SerializeToUtcTimestampMs { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_i64(chrono::Utc::now().timestamp_millis()) } } /// Structure storing all metrics while enforcing serialization support on them. #[derive(Default, Serialize)] pub struct FirecrackerMetrics { utc_timestamp_ms: SerializeToUtcTimestampMs, /// API Server related metrics. pub api_server: ApiServerMetrics, /// A block device's related metrics. pub block: BlockDeviceMetrics, /// Metrics related to API GET requests. pub get_api_requests: GetRequestsMetrics, /// Metrics relaetd to the i8042 device. pub i8042: I8042DeviceMetrics, /// Logging related metrics. pub logger: LoggerSystemMetrics, /// Metrics specific to MMDS functionality. pub mmds: MmdsMetrics, /// A network device's related metrics. pub net: NetDeviceMetrics, /// Metrics related to API PATCH requests. pub patch_api_requests: PatchRequestsMetrics, /// Metrics related to API PUT requests. pub put_api_requests: PutRequestsMetrics, /// Metrics related to seccomp filtering. pub seccomp: SeccompMetrics, /// Metrics related to a vcpu's functioning. pub vcpu: VcpuMetrics, /// Metrics related to the virtual machine manager. pub vmm: VmmMetrics, /// Metrics related to the UART device. pub uart: SerialDeviceMetrics, /// Memory usage metrics. pub memory: MemoryMetrics, } lazy_static! { /// Static instance used for handling metrics. /// pub static ref METRICS: FirecrackerMetrics = FirecrackerMetrics::default(); } #[cfg(test)] mod tests { extern crate serde_json; use super::*; use std::sync::Arc; use std::thread; #[test] fn test_metric() { let m1 = SimpleMetric::default(); m1.inc(); m1.inc(); m1.add(5); m1.inc(); assert_eq!(m1.count(), 8); let m2 = Arc::new(SharedMetric::default()); // We're going to create a number of threads that will attempt to increase this metric // in parallel. If everything goes fine we still can't be sure the synchronization works, // but it something fails, then we definitely have a problem :-s const NUM_THREADS_TO_SPAWN: usize = 4; const NUM_INCREMENTS_PER_THREAD: usize = 100000; const M2_INITIAL_COUNT: usize = 123; m2.add(M2_INITIAL_COUNT); let mut v = Vec::with_capacity(NUM_THREADS_TO_SPAWN); for _ in 0..NUM_THREADS_TO_SPAWN { let r = m2.clone(); v.push(thread::spawn(move || { for _ in 0..NUM_INCREMENTS_PER_THREAD { r.inc(); } })); } for handle in v { handle.join().unwrap(); } assert_eq!( m2.count(),
#[test] fn test_serialize() { let s = serde_json::to_string(&FirecrackerMetrics::default()); assert!(s.is_ok()); } }
M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD ); }
random_line_split
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/writes being atomic. //! * Exploit interior mutability and atomics being Sync to allow all methods (including the ones //! which are effectively mutable) to be callable on a global non-mut static. //! * Rely on `serde` to provide the actual serialization for logging the metrics. //! * Since all metrics start at 0, we implement the `Default` trait via derive for all of them, //! to avoid having to initialize everything by hand. //! //! Moreover, the value of a metric is currently NOT reset to 0 each time it's being logged. The //! current approach is to store two values (current and previous) and compute the delta between //! them each time we do a flush (i.e by serialization). There are a number of advantages //! to this approach, including: //! * We don't have to introduce an additional write (to reset the value) from the thread which //! does to actual logging, so less synchronization effort is required. //! * We don't have to worry at all that much about losing some data if logging fails for a while //! (this could be a concern, I guess). //! If if turns out this approach is not really what we want, it's pretty easy to resort to //! something else, while working behind the same interface. use std::sync::atomic::{AtomicUsize, Ordering}; use chrono; use serde::{Serialize, Serializer}; const SYSCALL_MAX: usize = 350; /// Used for defining new types of metrics that can be either incremented with an unit /// or an arbitrary amount of units. // This trait helps with writing less code. It has to be in scope (via an use directive) in order // for its methods to be available to call on structs that implement it. pub trait Metric { /// Adds `value` to the current counter. fn add(&self, value: usize); /// Increments by 1 unit the current counter. fn inc(&self) { self.add(1); } /// Returns current value of the counter. fn count(&self) -> usize; } /// Representation of a metric that is expected to be incremented from a single thread, so it /// can use simple loads and stores with no additional synchronization necessities. // Loads are currently Relaxed everywhere, because we don't do anything besides // logging the retrieved value (their outcome os not used to modify some memory location in a // potentially inconsistent manner). There's no way currently to make sure a SimpleMetric is only // incremented by a single thread, this has to be enforced via judicious use (although, every // non-vCPU related metric is associated with a particular thread, so it shouldn't be that easy // to misuse SimpleMetric fields). #[derive(Default)] pub struct SimpleMetric(AtomicUsize); impl Metric for SimpleMetric { fn add(&self, value: usize) { let ref count = self.0; count.store(count.load(Ordering::Relaxed) + value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SimpleMetric { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize(). serializer.serialize_u64(self.0.load(Ordering::Relaxed) as u64) } } /// Representation of a metric that is expected to be incremented from more than one thread, so more /// synchronization is necessary. // It's currently used for vCPU metrics. An alternative here would be // to have one instance of every metric for each thread (like a per-thread SimpleMetric), and to // aggregate them when logging. However this probably overkill unless we have a lot of vCPUs // incrementing metrics very often. Still, it's there if we ever need it :-s #[derive(Default)] // We will be keeping two values for each metric for being able to reset // counters on each metric. // 1st member - current value being updated // 2nd member - old value that gets the current value whenever metrics is flushed to disk pub struct SharedMetric(AtomicUsize, AtomicUsize); impl Metric for SharedMetric { // While the order specified for this operation is still Relaxed, the actual instruction will // be an asm "LOCK; something" and thus atomic across multiple threads, simply because of the // fetch_and_add (as opposed to "store(load() + 1)") implementation for atomics. // TODO: would a stronger ordering make a difference here? fn add(&self, value: usize) { self.0.fetch_add(value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SharedMetric { /// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the /// flushing of metrics. /// !!! Any print of the metrics will also reset them. Use with caution !!! fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize() for some reason :( let snapshot = self.0.load(Ordering::Relaxed); let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64); if res.is_ok() { self.1.store(snapshot, Ordering::Relaxed); } res } } // The following structs are used to define a certain organization for the set of metrics we // are interested in. Whenever the name of a field differs from its ideal textual representation // in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it. /// Metrics related to the internal API server. #[derive(Default, Serialize)] pub struct ApiServerMetrics { /// Measures the process's startup time in microseconds. pub process_startup_time_us: SharedMetric, /// Measures the cpu's startup time in microseconds. pub process_startup_time_cpu_us: SharedMetric, /// Number of failures on API requests triggered by internal errors. pub sync_outcome_fails: SharedMetric, /// Number of timeouts during communication with the VMM. pub sync_vmm_send_timeout_count: SharedMetric, } /// Metrics specific to GET API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct GetRequestsMetrics { /// Number of GETs for getting information on the instance. pub instance_info_count: SharedMetric, /// Number of failures when obtaining information on the current instance. pub instance_info_fails: SharedMetric, /// Number of GETs for getting status on attaching machine configuration. pub machine_cfg_count: SharedMetric, /// Number of failures during GETs for getting information on the instance. pub machine_cfg_fails: SharedMetric, } /// Metrics specific to PUT API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PutRequestsMetrics { /// Number of PUTs triggering an action on the VM. pub actions_count: SharedMetric, /// Number of failures in triggering an action on the VM. pub actions_fails: SharedMetric, /// Number of PUTs for attaching source of boot. pub boot_source_count: SharedMetric, /// Number of failures during attaching source of boot. pub boot_source_fails: SharedMetric, /// Number of PUTs triggering a block attach. pub drive_count: SharedMetric, /// Number of failures in attaching a block device. pub drive_fails: SharedMetric, /// Number of PUTs for initializing the logging system. pub logger_count: SharedMetric, /// Number of failures in initializing the logging system. pub logger_fails: SharedMetric, /// Number of PUTs for configuring the machine. pub machine_cfg_count: SharedMetric, /// Number of failures in configuring the machine. pub machine_cfg_fails: SharedMetric, /// Number of PUTs for creating a new network interface. pub network_count: SharedMetric, /// Number of failures in creating a new network interface. pub network_fails: SharedMetric, } /// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PatchRequestsMetrics { /// Number of tries to PATCH a block device. pub drive_count: SharedMetric, /// Number of failures in PATCHing a block device. pub drive_fails: SharedMetric, } /// Block Device associated metrics. #[derive(Default, Serialize)] pub struct BlockDeviceMetrics { /// Number of times when activate failed on a block device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a block device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a block device failed. pub event_fails: SharedMetric, /// Number of failures in executing a request on a block device. pub execute_fails: SharedMetric, /// Number of invalid requests received for this block device. pub invalid_reqs_count: SharedMetric, /// Number of flushes operation triggered on this block device. pub flush_count: SharedMetric, /// Number of events triggerd on the queue of this block device. pub queue_event_count: SharedMetric, /// Number of events ratelimiter-related. pub rate_limiter_event_count: SharedMetric, /// Number of update operation triggered on this block device. pub update_count: SharedMetric, /// Number of failures while doing update on this block device. pub update_fails: SharedMetric, /// Number of bytes read by this block device. pub read_count: SharedMetric, /// Number of bytes written by this block device. pub write_count: SharedMetric, } /// Metrics specific to the i8042 device. #[derive(Default, Serialize)] pub struct I8042DeviceMetrics { /// Errors triggered while using the i8042 device. pub error_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_read_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_write_count: SharedMetric, /// Bytes read by this device. pub read_count: SharedMetric, /// Number of resets done by this device. pub reset_count: SharedMetric, /// Bytes written by this device. pub write_count: SharedMetric, } /// Metrics for the logging subsystem. #[derive(Default, Serialize)] pub struct LoggerSystemMetrics { /// Number of misses on flushing metrics. pub missed_metrics_count: SharedMetric, /// Number of errors during metrics handling. pub metrics_fails: SharedMetric, /// Number of misses on logging human readable content. pub missed_log_count: SharedMetric, /// Number of errors while trying to log human readable content. pub log_fails: SharedMetric, } /// Metrics for the MMDS functionality. #[derive(Default, Serialize)] pub struct MmdsMetrics { /// Number of frames rerouted to MMDS. pub rx_accepted: SharedMetric, /// Number of errors while handling a frame through MMDS. pub rx_accepted_err: SharedMetric, /// Number of uncommon events encountered while processing packets through MMDS. pub rx_accepted_unusual: SharedMetric, /// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS. pub rx_bad_eth: SharedMetric, /// The total number of bytes sent by the MMDS. pub tx_bytes: SharedMetric, /// The number of errors raised by the MMDS while attempting to send frames/packets/segments. pub tx_errors: SharedMetric, /// The number of frames sent by the MMDS. pub tx_frames: SharedMetric, /// The number of connections successfully accepted by the MMDS TCP handler. pub connections_created: SharedMetric, /// The number of connections cleaned up by the MMDS TCP handler. pub connections_destroyed: SharedMetric, } /// Network-related metrics. #[derive(Default, Serialize)] pub struct NetDeviceMetrics { /// Number of times when activate failed on a network device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a network device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a network device failed. pub event_fails: SharedMetric, /// Number of events associated with the receiving queue. pub rx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the receiving path. pub rx_event_rate_limiter_count: SharedMetric, /// Number of events received on the associated tap. pub rx_tap_event_count: SharedMetric, /// Number of bytes received. pub rx_bytes_count: SharedMetric, /// Number of packets received. pub rx_packets_count: SharedMetric, /// Number of errors while receiving data. pub rx_fails: SharedMetric, /// Number of transmitted bytes. pub tx_bytes_count: SharedMetric, /// Number of errors while transmitting data. pub tx_fails: SharedMetric, /// Number of transmitted packets. pub tx_packets_count: SharedMetric, /// Number of events associated with the transmitting queue. pub tx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the transmitting path. pub tx_rate_limiter_event_count: SharedMetric, } /// Metrics for the seccomp filtering. #[derive(Serialize)] pub struct SeccompMetrics { /// Number of black listed syscalls. pub bad_syscalls: Vec<SharedMetric>, /// Number of errors inside the seccomp filtering. pub num_faults: SharedMetric, } impl Default for SeccompMetrics { fn
() -> SeccompMetrics { let mut def_syscalls = vec![]; for _syscall in 0..SYSCALL_MAX { def_syscalls.push(SharedMetric::default()); } SeccompMetrics { num_faults: SharedMetric::default(), bad_syscalls: def_syscalls, } } } /// Metrics specific to the UART device. #[derive(Default, Serialize)] pub struct SerialDeviceMetrics { /// Errors triggered while using the UART device. pub error_count: SharedMetric, /// Number of flush operations. pub flush_count: SharedMetric, /// Number of read calls that did not trigger a read. pub missed_read_count: SharedMetric, /// Number of write calls that did not trigger a write. pub missed_write_count: SharedMetric, /// Number of succeeded read calls. pub read_count: SharedMetric, /// Number of succeeded write calls. pub write_count: SharedMetric, } /// Metrics specific to VCPUs' mode of functioning. #[derive(Default, Serialize)] pub struct VcpuMetrics { /// Number of KVM exits for handling input IO. pub exit_io_in: SharedMetric, /// Number of KVM exits for handling output IO. pub exit_io_out: SharedMetric, /// Number of KVM exits for handling MMIO reads. pub exit_mmio_read: SharedMetric, /// Number of KVM exits for handling MMIO writes. pub exit_mmio_write: SharedMetric, /// Number of errors during this VCPU's run. pub failures: SharedMetric, /// Failures in configuring the CPUID. pub fitler_cpuid: SharedMetric, } /// Metrics specific to the machine manager as a whole. #[derive(Default, Serialize)] pub struct VmmMetrics { /// Number of device related events received for a VM. pub device_events: SharedMetric, /// Metric for signaling a panic has occurred. pub panic_count: SharedMetric, } /// Memory usage metrics. #[derive(Default, Serialize)] pub struct MemoryMetrics { /// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`. pub dirty_pages: SharedMetric, } // The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized. #[derive(Default)] struct SerializeToUtcTimestampMs; impl Serialize for SerializeToUtcTimestampMs { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_i64(chrono::Utc::now().timestamp_millis()) } } /// Structure storing all metrics while enforcing serialization support on them. #[derive(Default, Serialize)] pub struct FirecrackerMetrics { utc_timestamp_ms: SerializeToUtcTimestampMs, /// API Server related metrics. pub api_server: ApiServerMetrics, /// A block device's related metrics. pub block: BlockDeviceMetrics, /// Metrics related to API GET requests. pub get_api_requests: GetRequestsMetrics, /// Metrics relaetd to the i8042 device. pub i8042: I8042DeviceMetrics, /// Logging related metrics. pub logger: LoggerSystemMetrics, /// Metrics specific to MMDS functionality. pub mmds: MmdsMetrics, /// A network device's related metrics. pub net: NetDeviceMetrics, /// Metrics related to API PATCH requests. pub patch_api_requests: PatchRequestsMetrics, /// Metrics related to API PUT requests. pub put_api_requests: PutRequestsMetrics, /// Metrics related to seccomp filtering. pub seccomp: SeccompMetrics, /// Metrics related to a vcpu's functioning. pub vcpu: VcpuMetrics, /// Metrics related to the virtual machine manager. pub vmm: VmmMetrics, /// Metrics related to the UART device. pub uart: SerialDeviceMetrics, /// Memory usage metrics. pub memory: MemoryMetrics, } lazy_static! { /// Static instance used for handling metrics. /// pub static ref METRICS: FirecrackerMetrics = FirecrackerMetrics::default(); } #[cfg(test)] mod tests { extern crate serde_json; use super::*; use std::sync::Arc; use std::thread; #[test] fn test_metric() { let m1 = SimpleMetric::default(); m1.inc(); m1.inc(); m1.add(5); m1.inc(); assert_eq!(m1.count(), 8); let m2 = Arc::new(SharedMetric::default()); // We're going to create a number of threads that will attempt to increase this metric // in parallel. If everything goes fine we still can't be sure the synchronization works, // but it something fails, then we definitely have a problem :-s const NUM_THREADS_TO_SPAWN: usize = 4; const NUM_INCREMENTS_PER_THREAD: usize = 100000; const M2_INITIAL_COUNT: usize = 123; m2.add(M2_INITIAL_COUNT); let mut v = Vec::with_capacity(NUM_THREADS_TO_SPAWN); for _ in 0..NUM_THREADS_TO_SPAWN { let r = m2.clone(); v.push(thread::spawn(move || { for _ in 0..NUM_INCREMENTS_PER_THREAD { r.inc(); } })); } for handle in v { handle.join().unwrap(); } assert_eq!( m2.count(), M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD ); } #[test] fn test_serialize() { let s = serde_json::to_string(&FirecrackerMetrics::default()); assert!(s.is_ok()); } }
default
identifier_name
metrics.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //! Defines the metrics system. //! //! # Design //! The main design goals of this system are: //! * Use lockless operations, preferably ones that don't require anything other than //! simple reads/writes being atomic. //! * Exploit interior mutability and atomics being Sync to allow all methods (including the ones //! which are effectively mutable) to be callable on a global non-mut static. //! * Rely on `serde` to provide the actual serialization for logging the metrics. //! * Since all metrics start at 0, we implement the `Default` trait via derive for all of them, //! to avoid having to initialize everything by hand. //! //! Moreover, the value of a metric is currently NOT reset to 0 each time it's being logged. The //! current approach is to store two values (current and previous) and compute the delta between //! them each time we do a flush (i.e by serialization). There are a number of advantages //! to this approach, including: //! * We don't have to introduce an additional write (to reset the value) from the thread which //! does to actual logging, so less synchronization effort is required. //! * We don't have to worry at all that much about losing some data if logging fails for a while //! (this could be a concern, I guess). //! If if turns out this approach is not really what we want, it's pretty easy to resort to //! something else, while working behind the same interface. use std::sync::atomic::{AtomicUsize, Ordering}; use chrono; use serde::{Serialize, Serializer}; const SYSCALL_MAX: usize = 350; /// Used for defining new types of metrics that can be either incremented with an unit /// or an arbitrary amount of units. // This trait helps with writing less code. It has to be in scope (via an use directive) in order // for its methods to be available to call on structs that implement it. pub trait Metric { /// Adds `value` to the current counter. fn add(&self, value: usize); /// Increments by 1 unit the current counter. fn inc(&self) { self.add(1); } /// Returns current value of the counter. fn count(&self) -> usize; } /// Representation of a metric that is expected to be incremented from a single thread, so it /// can use simple loads and stores with no additional synchronization necessities. // Loads are currently Relaxed everywhere, because we don't do anything besides // logging the retrieved value (their outcome os not used to modify some memory location in a // potentially inconsistent manner). There's no way currently to make sure a SimpleMetric is only // incremented by a single thread, this has to be enforced via judicious use (although, every // non-vCPU related metric is associated with a particular thread, so it shouldn't be that easy // to misuse SimpleMetric fields). #[derive(Default)] pub struct SimpleMetric(AtomicUsize); impl Metric for SimpleMetric { fn add(&self, value: usize) { let ref count = self.0; count.store(count.load(Ordering::Relaxed) + value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SimpleMetric { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize(). serializer.serialize_u64(self.0.load(Ordering::Relaxed) as u64) } } /// Representation of a metric that is expected to be incremented from more than one thread, so more /// synchronization is necessary. // It's currently used for vCPU metrics. An alternative here would be // to have one instance of every metric for each thread (like a per-thread SimpleMetric), and to // aggregate them when logging. However this probably overkill unless we have a lot of vCPUs // incrementing metrics very often. Still, it's there if we ever need it :-s #[derive(Default)] // We will be keeping two values for each metric for being able to reset // counters on each metric. // 1st member - current value being updated // 2nd member - old value that gets the current value whenever metrics is flushed to disk pub struct SharedMetric(AtomicUsize, AtomicUsize); impl Metric for SharedMetric { // While the order specified for this operation is still Relaxed, the actual instruction will // be an asm "LOCK; something" and thus atomic across multiple threads, simply because of the // fetch_and_add (as opposed to "store(load() + 1)") implementation for atomics. // TODO: would a stronger ordering make a difference here? fn add(&self, value: usize) { self.0.fetch_add(value, Ordering::Relaxed); } fn count(&self) -> usize { self.0.load(Ordering::Relaxed) } } impl Serialize for SharedMetric { /// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the /// flushing of metrics. /// !!! Any print of the metrics will also reset them. Use with caution !!! fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { // There's no serializer.serialize_usize() for some reason :( let snapshot = self.0.load(Ordering::Relaxed); let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64); if res.is_ok()
res } } // The following structs are used to define a certain organization for the set of metrics we // are interested in. Whenever the name of a field differs from its ideal textual representation // in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it. /// Metrics related to the internal API server. #[derive(Default, Serialize)] pub struct ApiServerMetrics { /// Measures the process's startup time in microseconds. pub process_startup_time_us: SharedMetric, /// Measures the cpu's startup time in microseconds. pub process_startup_time_cpu_us: SharedMetric, /// Number of failures on API requests triggered by internal errors. pub sync_outcome_fails: SharedMetric, /// Number of timeouts during communication with the VMM. pub sync_vmm_send_timeout_count: SharedMetric, } /// Metrics specific to GET API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct GetRequestsMetrics { /// Number of GETs for getting information on the instance. pub instance_info_count: SharedMetric, /// Number of failures when obtaining information on the current instance. pub instance_info_fails: SharedMetric, /// Number of GETs for getting status on attaching machine configuration. pub machine_cfg_count: SharedMetric, /// Number of failures during GETs for getting information on the instance. pub machine_cfg_fails: SharedMetric, } /// Metrics specific to PUT API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PutRequestsMetrics { /// Number of PUTs triggering an action on the VM. pub actions_count: SharedMetric, /// Number of failures in triggering an action on the VM. pub actions_fails: SharedMetric, /// Number of PUTs for attaching source of boot. pub boot_source_count: SharedMetric, /// Number of failures during attaching source of boot. pub boot_source_fails: SharedMetric, /// Number of PUTs triggering a block attach. pub drive_count: SharedMetric, /// Number of failures in attaching a block device. pub drive_fails: SharedMetric, /// Number of PUTs for initializing the logging system. pub logger_count: SharedMetric, /// Number of failures in initializing the logging system. pub logger_fails: SharedMetric, /// Number of PUTs for configuring the machine. pub machine_cfg_count: SharedMetric, /// Number of failures in configuring the machine. pub machine_cfg_fails: SharedMetric, /// Number of PUTs for creating a new network interface. pub network_count: SharedMetric, /// Number of failures in creating a new network interface. pub network_fails: SharedMetric, } /// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures. #[derive(Default, Serialize)] pub struct PatchRequestsMetrics { /// Number of tries to PATCH a block device. pub drive_count: SharedMetric, /// Number of failures in PATCHing a block device. pub drive_fails: SharedMetric, } /// Block Device associated metrics. #[derive(Default, Serialize)] pub struct BlockDeviceMetrics { /// Number of times when activate failed on a block device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a block device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a block device failed. pub event_fails: SharedMetric, /// Number of failures in executing a request on a block device. pub execute_fails: SharedMetric, /// Number of invalid requests received for this block device. pub invalid_reqs_count: SharedMetric, /// Number of flushes operation triggered on this block device. pub flush_count: SharedMetric, /// Number of events triggerd on the queue of this block device. pub queue_event_count: SharedMetric, /// Number of events ratelimiter-related. pub rate_limiter_event_count: SharedMetric, /// Number of update operation triggered on this block device. pub update_count: SharedMetric, /// Number of failures while doing update on this block device. pub update_fails: SharedMetric, /// Number of bytes read by this block device. pub read_count: SharedMetric, /// Number of bytes written by this block device. pub write_count: SharedMetric, } /// Metrics specific to the i8042 device. #[derive(Default, Serialize)] pub struct I8042DeviceMetrics { /// Errors triggered while using the i8042 device. pub error_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_read_count: SharedMetric, /// Number of superfluous read intents on this i8042 device. pub missed_write_count: SharedMetric, /// Bytes read by this device. pub read_count: SharedMetric, /// Number of resets done by this device. pub reset_count: SharedMetric, /// Bytes written by this device. pub write_count: SharedMetric, } /// Metrics for the logging subsystem. #[derive(Default, Serialize)] pub struct LoggerSystemMetrics { /// Number of misses on flushing metrics. pub missed_metrics_count: SharedMetric, /// Number of errors during metrics handling. pub metrics_fails: SharedMetric, /// Number of misses on logging human readable content. pub missed_log_count: SharedMetric, /// Number of errors while trying to log human readable content. pub log_fails: SharedMetric, } /// Metrics for the MMDS functionality. #[derive(Default, Serialize)] pub struct MmdsMetrics { /// Number of frames rerouted to MMDS. pub rx_accepted: SharedMetric, /// Number of errors while handling a frame through MMDS. pub rx_accepted_err: SharedMetric, /// Number of uncommon events encountered while processing packets through MMDS. pub rx_accepted_unusual: SharedMetric, /// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS. pub rx_bad_eth: SharedMetric, /// The total number of bytes sent by the MMDS. pub tx_bytes: SharedMetric, /// The number of errors raised by the MMDS while attempting to send frames/packets/segments. pub tx_errors: SharedMetric, /// The number of frames sent by the MMDS. pub tx_frames: SharedMetric, /// The number of connections successfully accepted by the MMDS TCP handler. pub connections_created: SharedMetric, /// The number of connections cleaned up by the MMDS TCP handler. pub connections_destroyed: SharedMetric, } /// Network-related metrics. #[derive(Default, Serialize)] pub struct NetDeviceMetrics { /// Number of times when activate failed on a network device. pub activate_fails: SharedMetric, /// Number of times when interacting with the space config of a network device failed. pub cfg_fails: SharedMetric, /// Number of times when handling events on a network device failed. pub event_fails: SharedMetric, /// Number of events associated with the receiving queue. pub rx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the receiving path. pub rx_event_rate_limiter_count: SharedMetric, /// Number of events received on the associated tap. pub rx_tap_event_count: SharedMetric, /// Number of bytes received. pub rx_bytes_count: SharedMetric, /// Number of packets received. pub rx_packets_count: SharedMetric, /// Number of errors while receiving data. pub rx_fails: SharedMetric, /// Number of transmitted bytes. pub tx_bytes_count: SharedMetric, /// Number of errors while transmitting data. pub tx_fails: SharedMetric, /// Number of transmitted packets. pub tx_packets_count: SharedMetric, /// Number of events associated with the transmitting queue. pub tx_queue_event_count: SharedMetric, /// Number of events associated with the rate limiter installed on the transmitting path. pub tx_rate_limiter_event_count: SharedMetric, } /// Metrics for the seccomp filtering. #[derive(Serialize)] pub struct SeccompMetrics { /// Number of black listed syscalls. pub bad_syscalls: Vec<SharedMetric>, /// Number of errors inside the seccomp filtering. pub num_faults: SharedMetric, } impl Default for SeccompMetrics { fn default() -> SeccompMetrics { let mut def_syscalls = vec![]; for _syscall in 0..SYSCALL_MAX { def_syscalls.push(SharedMetric::default()); } SeccompMetrics { num_faults: SharedMetric::default(), bad_syscalls: def_syscalls, } } } /// Metrics specific to the UART device. #[derive(Default, Serialize)] pub struct SerialDeviceMetrics { /// Errors triggered while using the UART device. pub error_count: SharedMetric, /// Number of flush operations. pub flush_count: SharedMetric, /// Number of read calls that did not trigger a read. pub missed_read_count: SharedMetric, /// Number of write calls that did not trigger a write. pub missed_write_count: SharedMetric, /// Number of succeeded read calls. pub read_count: SharedMetric, /// Number of succeeded write calls. pub write_count: SharedMetric, } /// Metrics specific to VCPUs' mode of functioning. #[derive(Default, Serialize)] pub struct VcpuMetrics { /// Number of KVM exits for handling input IO. pub exit_io_in: SharedMetric, /// Number of KVM exits for handling output IO. pub exit_io_out: SharedMetric, /// Number of KVM exits for handling MMIO reads. pub exit_mmio_read: SharedMetric, /// Number of KVM exits for handling MMIO writes. pub exit_mmio_write: SharedMetric, /// Number of errors during this VCPU's run. pub failures: SharedMetric, /// Failures in configuring the CPUID. pub fitler_cpuid: SharedMetric, } /// Metrics specific to the machine manager as a whole. #[derive(Default, Serialize)] pub struct VmmMetrics { /// Number of device related events received for a VM. pub device_events: SharedMetric, /// Metric for signaling a panic has occurred. pub panic_count: SharedMetric, } /// Memory usage metrics. #[derive(Default, Serialize)] pub struct MemoryMetrics { /// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`. pub dirty_pages: SharedMetric, } // The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized. #[derive(Default)] struct SerializeToUtcTimestampMs; impl Serialize for SerializeToUtcTimestampMs { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_i64(chrono::Utc::now().timestamp_millis()) } } /// Structure storing all metrics while enforcing serialization support on them. #[derive(Default, Serialize)] pub struct FirecrackerMetrics { utc_timestamp_ms: SerializeToUtcTimestampMs, /// API Server related metrics. pub api_server: ApiServerMetrics, /// A block device's related metrics. pub block: BlockDeviceMetrics, /// Metrics related to API GET requests. pub get_api_requests: GetRequestsMetrics, /// Metrics relaetd to the i8042 device. pub i8042: I8042DeviceMetrics, /// Logging related metrics. pub logger: LoggerSystemMetrics, /// Metrics specific to MMDS functionality. pub mmds: MmdsMetrics, /// A network device's related metrics. pub net: NetDeviceMetrics, /// Metrics related to API PATCH requests. pub patch_api_requests: PatchRequestsMetrics, /// Metrics related to API PUT requests. pub put_api_requests: PutRequestsMetrics, /// Metrics related to seccomp filtering. pub seccomp: SeccompMetrics, /// Metrics related to a vcpu's functioning. pub vcpu: VcpuMetrics, /// Metrics related to the virtual machine manager. pub vmm: VmmMetrics, /// Metrics related to the UART device. pub uart: SerialDeviceMetrics, /// Memory usage metrics. pub memory: MemoryMetrics, } lazy_static! { /// Static instance used for handling metrics. /// pub static ref METRICS: FirecrackerMetrics = FirecrackerMetrics::default(); } #[cfg(test)] mod tests { extern crate serde_json; use super::*; use std::sync::Arc; use std::thread; #[test] fn test_metric() { let m1 = SimpleMetric::default(); m1.inc(); m1.inc(); m1.add(5); m1.inc(); assert_eq!(m1.count(), 8); let m2 = Arc::new(SharedMetric::default()); // We're going to create a number of threads that will attempt to increase this metric // in parallel. If everything goes fine we still can't be sure the synchronization works, // but it something fails, then we definitely have a problem :-s const NUM_THREADS_TO_SPAWN: usize = 4; const NUM_INCREMENTS_PER_THREAD: usize = 100000; const M2_INITIAL_COUNT: usize = 123; m2.add(M2_INITIAL_COUNT); let mut v = Vec::with_capacity(NUM_THREADS_TO_SPAWN); for _ in 0..NUM_THREADS_TO_SPAWN { let r = m2.clone(); v.push(thread::spawn(move || { for _ in 0..NUM_INCREMENTS_PER_THREAD { r.inc(); } })); } for handle in v { handle.join().unwrap(); } assert_eq!( m2.count(), M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD ); } #[test] fn test_serialize() { let s = serde_json::to_string(&FirecrackerMetrics::default()); assert!(s.is_ok()); } }
{ self.1.store(snapshot, Ordering::Relaxed); }
conditional_block
collocations.py
# Natural Language Toolkit: Collocations and Association Measures # # Copyright (C) 2001-2023 NLTK Project # Author: Joel Nothman <jnothman@student.usyd.edu.au> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT # """ Tools to identify collocations --- words that often appear consecutively --- within corpora. They may also be used to find other associations between word occurrences. See Manning and Schutze ch. 5 at https://nlp.stanford.edu/fsnlp/promo/colloc.pdf and the Text::NSP Perl package at http://ngram.sourceforge.net Finding collocations requires first calculating the frequencies of words and their appearance in the context of other words. Often the collection of words will then requiring filtering to only retain useful content terms. Each ngram of words may then be scored according to some association measure, in order to determine the relative likelihood of each ngram being a collocation. The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide these functionalities, dependent on being provided a function which scores a ngram given appropriate frequency counts. A number of standard association measures are provided in bigram_measures and trigram_measures. """ # Possible TODOs: # - consider the distinction between f(x,_) and f(x) and whether our # approximation is good enough for fragmented data, and mention it # - add a n-gram collocation finder with measures which only utilise n-gram # and unigram counts (raw_freq, pmi, student_t) import itertools as _itertools # these two unused imports are referenced in collocations.doctest from nltk.metrics import ( BigramAssocMeasures, ContingencyMeasures, QuadgramAssocMeasures, TrigramAssocMeasures, ) from nltk.metrics.spearman import ranks_from_scores, spearman_correlation from nltk.probability import FreqDist from nltk.util import ngrams class AbstractCollocationFinder: """ An abstract base class for collocation finders whose purpose is to collect collocation candidate frequencies, filter and rank them. As a minimum, collocation finders require the frequencies of each word in a corpus, and the joint frequency of word tuples. This data should be provided through nltk.probability.FreqDist objects or an identical interface. """ def __init__(self, word_fd, ngram_fd): self.word_fd = word_fd self.N = word_fd.N() self.ngram_fd = ngram_fd @classmethod def _build_new_documents( cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None ): """ Pad the document with the place holder according to the window_size """ padding = (pad_symbol,) * (window_size - 1) if pad_right: return _itertools.chain.from_iterable( _itertools.chain(doc, padding) for doc in documents ) if pad_left: return _itertools.chain.from_iterable( _itertools.chain(padding, doc) for doc in documents ) @classmethod def from_documents(cls, documents): """Constructs a collocation finder given a collection of documents, each of which is a list (or iterable) of tokens. """ # return cls.from_words(_itertools.chain(*documents)) return cls.from_words( cls._build_new_documents(documents, cls.default_ws, pad_right=True) ) @staticmethod def _ngram_freqdist(words, n): return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1)) def _apply_filter(self, fn=lambda ngram, freq: False): """Generic filter removes ngrams from the frequency distribution if the function returns True when passed an ngram tuple. """ tmp_ngram = FreqDist() for ngram, freq in self.ngram_fd.items(): if not fn(ngram, freq): tmp_ngram[ngram] = freq self.ngram_fd = tmp_ngram def apply_freq_filter(self, min_freq): """Removes candidate ngrams which have frequency less than min_freq.""" self._apply_filter(lambda ng, freq: freq < min_freq) def apply_ngram_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...) evaluates to True. """ self._apply_filter(lambda ng, f: fn(*ng)) def apply_word_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2), ...) evaluates to True. """ self._apply_filter(lambda ng, f: any(fn(w) for w in ng)) def _score_ngrams(self, score_fn): """Generates of (ngram, score) pairs as determined by the scoring function provided. """ for tup in self.ngram_fd: score = self.score_ngram(score_fn, *tup) if score is not None: yield tup, score def
(self, score_fn): """Returns a sequence of (ngram, score) pairs ordered from highest to lowest score, as determined by the scoring function provided. """ return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0])) def nbest(self, score_fn, n): """Returns the top n ngrams when scored by the given function.""" return [p for p, s in self.score_ngrams(score_fn)[:n]] def above_score(self, score_fn, min_score): """Returns a sequence of ngrams, ordered by decreasing score, whose scores each exceed the given minimum score. """ for ngram, score in self.score_ngrams(score_fn): if score > min_score: yield ngram else: break class BigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of bigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 2 def __init__(self, word_fd, bigram_fd, window_size=2): """Construct a BigramCollocationFinder, given FreqDists for appearances of words and (possibly non-contiguous) bigrams. """ AbstractCollocationFinder.__init__(self, word_fd, bigram_fd) self.window_size = window_size @classmethod def from_words(cls, words, window_size=2): """Construct a BigramCollocationFinder for all bigrams in the given sequence. When window_size > 2, count non-contiguous bigrams, in the style of Church and Hanks's (1990) association ratio. """ wfd = FreqDist() bfd = FreqDist() if window_size < 2: raise ValueError("Specify window_size at least 2") for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue wfd[w1] += 1 for w2 in window[1:]: if w2 is not None: bfd[(w1, w2)] += 1 return cls(wfd, bfd, window_size=window_size) def score_ngram(self, score_fn, w1, w2): """Returns the score for a given bigram using the given scoring function. Following Church and Hanks (1990), counts are scaled by a factor of 1/(window_size - 1). """ n_all = self.N n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0) if not n_ii: return n_ix = self.word_fd[w1] n_xi = self.word_fd[w2] return score_fn(n_ii, (n_ix, n_xi), n_all) class TrigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of trigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 3 def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): """Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams. """ AbstractCollocationFinder.__init__(self, word_fd, trigram_fd) self.wildcard_fd = wildcard_fd self.bigram_fd = bigram_fd @classmethod def from_words(cls, words, window_size=3): """Construct a TrigramCollocationFinder for all trigrams in the given sequence. """ if window_size < 3: raise ValueError("Specify window_size at least 3") wfd = FreqDist() wildfd = FreqDist() bfd = FreqDist() tfd = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3 in _itertools.combinations(window[1:], 2): wfd[w1] += 1 if w2 is None: continue bfd[(w1, w2)] += 1 if w3 is None: continue wildfd[(w1, w3)] += 1 tfd[(w1, w2, w3)] += 1 return cls(wfd, bfd, wildfd, tfd) def bigram_finder(self): """Constructs a bigram collocation finder with the bigram and unigram data from this finder. Note that this does not include any filtering applied to this finder. """ return BigramCollocationFinder(self.word_fd, self.bigram_fd) def score_ngram(self, score_fn, w1, w2, w3): """Returns the score for a given trigram using the given scoring function. """ n_all = self.N n_iii = self.ngram_fd[(w1, w2, w3)] if not n_iii: return n_iix = self.bigram_fd[(w1, w2)] n_ixi = self.wildcard_fd[(w1, w3)] n_xii = self.bigram_fd[(w2, w3)] n_ixx = self.word_fd[w1] n_xix = self.word_fd[w2] n_xxi = self.word_fd[w3] return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all) class QuadgramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of quadgram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 4 def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii): """Construct a QuadgramCollocationFinder, given FreqDists for appearances of words, bigrams, trigrams, two words with one word and two words between them, three words with a word between them in both variations. """ AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd) self.iii = iii self.ii = ii self.ixi = ixi self.ixxi = ixxi self.iixi = iixi self.ixii = ixii @classmethod def from_words(cls, words, window_size=4): if window_size < 4: raise ValueError("Specify window_size at least 4") ixxx = FreqDist() iiii = FreqDist() ii = FreqDist() iii = FreqDist() ixi = FreqDist() ixxi = FreqDist() iixi = FreqDist() ixii = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3, w4 in _itertools.combinations(window[1:], 3): ixxx[w1] += 1 if w2 is None: continue ii[(w1, w2)] += 1 if w3 is None: continue iii[(w1, w2, w3)] += 1 ixi[(w1, w3)] += 1 if w4 is None: continue iiii[(w1, w2, w3, w4)] += 1 ixxi[(w1, w4)] += 1 ixii[(w1, w3, w4)] += 1 iixi[(w1, w2, w4)] += 1 return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii) def score_ngram(self, score_fn, w1, w2, w3, w4): n_all = self.N n_iiii = self.ngram_fd[(w1, w2, w3, w4)] if not n_iiii: return n_iiix = self.iii[(w1, w2, w3)] n_xiii = self.iii[(w2, w3, w4)] n_iixi = self.iixi[(w1, w2, w4)] n_ixii = self.ixii[(w1, w3, w4)] n_iixx = self.ii[(w1, w2)] n_xxii = self.ii[(w3, w4)] n_xiix = self.ii[(w2, w3)] n_ixix = self.ixi[(w1, w3)] n_ixxi = self.ixxi[(w1, w4)] n_xixi = self.ixi[(w2, w4)] n_ixxx = self.word_fd[w1] n_xixx = self.word_fd[w2] n_xxix = self.word_fd[w3] n_xxxi = self.word_fd[w4] return score_fn( n_iiii, (n_iiix, n_iixi, n_ixii, n_xiii), (n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix), (n_ixxx, n_xixx, n_xxix, n_xxxi), n_all, ) def demo(scorer=None, compare_scorer=None): """Finds bigram collocations in the files of the WebText corpus.""" from nltk.metrics import ( BigramAssocMeasures, ranks_from_scores, spearman_correlation, ) if scorer is None: scorer = BigramAssocMeasures.likelihood_ratio if compare_scorer is None: compare_scorer = BigramAssocMeasures.raw_freq from nltk.corpus import stopwords, webtext ignored_words = stopwords.words("english") word_filter = lambda w: len(w) < 3 or w.lower() in ignored_words for file in webtext.fileids(): words = [word.lower() for word in webtext.words(file)] cf = BigramCollocationFinder.from_words(words) cf.apply_freq_filter(3) cf.apply_word_filter(word_filter) corr = spearman_correlation( ranks_from_scores(cf.score_ngrams(scorer)), ranks_from_scores(cf.score_ngrams(compare_scorer)), ) print(file) print("\t", [" ".join(tup) for tup in cf.nbest(scorer, 15)]) print(f"\t Correlation to {compare_scorer.__name__}: {corr:0.4f}") # Slows down loading too much # bigram_measures = BigramAssocMeasures() # trigram_measures = TrigramAssocMeasures() if __name__ == "__main__": import sys from nltk.metrics import BigramAssocMeasures try: scorer = eval("BigramAssocMeasures." + sys.argv[1]) except IndexError: scorer = None try: compare_scorer = eval("BigramAssocMeasures." + sys.argv[2]) except IndexError: compare_scorer = None demo(scorer, compare_scorer) __all__ = [ "BigramCollocationFinder", "TrigramCollocationFinder", "QuadgramCollocationFinder", ]
score_ngrams
identifier_name
collocations.py
# Natural Language Toolkit: Collocations and Association Measures # # Copyright (C) 2001-2023 NLTK Project # Author: Joel Nothman <jnothman@student.usyd.edu.au> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT # """ Tools to identify collocations --- words that often appear consecutively --- within corpora. They may also be used to find other associations between word occurrences. See Manning and Schutze ch. 5 at https://nlp.stanford.edu/fsnlp/promo/colloc.pdf and the Text::NSP Perl package at http://ngram.sourceforge.net Finding collocations requires first calculating the frequencies of words and their appearance in the context of other words. Often the collection of words will then requiring filtering to only retain useful content terms. Each ngram of words may then be scored according to some association measure, in order to determine the relative likelihood of each ngram being a collocation. The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide these functionalities, dependent on being provided a function which scores a ngram given appropriate frequency counts. A number of standard association measures are provided in bigram_measures and trigram_measures. """ # Possible TODOs: # - consider the distinction between f(x,_) and f(x) and whether our # approximation is good enough for fragmented data, and mention it # - add a n-gram collocation finder with measures which only utilise n-gram # and unigram counts (raw_freq, pmi, student_t) import itertools as _itertools # these two unused imports are referenced in collocations.doctest from nltk.metrics import ( BigramAssocMeasures, ContingencyMeasures, QuadgramAssocMeasures, TrigramAssocMeasures, ) from nltk.metrics.spearman import ranks_from_scores, spearman_correlation from nltk.probability import FreqDist from nltk.util import ngrams class AbstractCollocationFinder: """ An abstract base class for collocation finders whose purpose is to collect collocation candidate frequencies, filter and rank them. As a minimum, collocation finders require the frequencies of each word in a corpus, and the joint frequency of word tuples. This data should be provided through nltk.probability.FreqDist objects or an identical interface. """ def __init__(self, word_fd, ngram_fd): self.word_fd = word_fd self.N = word_fd.N() self.ngram_fd = ngram_fd @classmethod def _build_new_documents( cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None ): """ Pad the document with the place holder according to the window_size """ padding = (pad_symbol,) * (window_size - 1) if pad_right: return _itertools.chain.from_iterable( _itertools.chain(doc, padding) for doc in documents ) if pad_left: return _itertools.chain.from_iterable( _itertools.chain(padding, doc) for doc in documents ) @classmethod def from_documents(cls, documents): """Constructs a collocation finder given a collection of documents, each of which is a list (or iterable) of tokens. """ # return cls.from_words(_itertools.chain(*documents)) return cls.from_words( cls._build_new_documents(documents, cls.default_ws, pad_right=True) ) @staticmethod def _ngram_freqdist(words, n): return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1)) def _apply_filter(self, fn=lambda ngram, freq: False): """Generic filter removes ngrams from the frequency distribution if the function returns True when passed an ngram tuple. """ tmp_ngram = FreqDist() for ngram, freq in self.ngram_fd.items(): if not fn(ngram, freq): tmp_ngram[ngram] = freq self.ngram_fd = tmp_ngram def apply_freq_filter(self, min_freq):
def apply_ngram_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...) evaluates to True. """ self._apply_filter(lambda ng, f: fn(*ng)) def apply_word_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2), ...) evaluates to True. """ self._apply_filter(lambda ng, f: any(fn(w) for w in ng)) def _score_ngrams(self, score_fn): """Generates of (ngram, score) pairs as determined by the scoring function provided. """ for tup in self.ngram_fd: score = self.score_ngram(score_fn, *tup) if score is not None: yield tup, score def score_ngrams(self, score_fn): """Returns a sequence of (ngram, score) pairs ordered from highest to lowest score, as determined by the scoring function provided. """ return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0])) def nbest(self, score_fn, n): """Returns the top n ngrams when scored by the given function.""" return [p for p, s in self.score_ngrams(score_fn)[:n]] def above_score(self, score_fn, min_score): """Returns a sequence of ngrams, ordered by decreasing score, whose scores each exceed the given minimum score. """ for ngram, score in self.score_ngrams(score_fn): if score > min_score: yield ngram else: break class BigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of bigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 2 def __init__(self, word_fd, bigram_fd, window_size=2): """Construct a BigramCollocationFinder, given FreqDists for appearances of words and (possibly non-contiguous) bigrams. """ AbstractCollocationFinder.__init__(self, word_fd, bigram_fd) self.window_size = window_size @classmethod def from_words(cls, words, window_size=2): """Construct a BigramCollocationFinder for all bigrams in the given sequence. When window_size > 2, count non-contiguous bigrams, in the style of Church and Hanks's (1990) association ratio. """ wfd = FreqDist() bfd = FreqDist() if window_size < 2: raise ValueError("Specify window_size at least 2") for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue wfd[w1] += 1 for w2 in window[1:]: if w2 is not None: bfd[(w1, w2)] += 1 return cls(wfd, bfd, window_size=window_size) def score_ngram(self, score_fn, w1, w2): """Returns the score for a given bigram using the given scoring function. Following Church and Hanks (1990), counts are scaled by a factor of 1/(window_size - 1). """ n_all = self.N n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0) if not n_ii: return n_ix = self.word_fd[w1] n_xi = self.word_fd[w2] return score_fn(n_ii, (n_ix, n_xi), n_all) class TrigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of trigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 3 def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): """Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams. """ AbstractCollocationFinder.__init__(self, word_fd, trigram_fd) self.wildcard_fd = wildcard_fd self.bigram_fd = bigram_fd @classmethod def from_words(cls, words, window_size=3): """Construct a TrigramCollocationFinder for all trigrams in the given sequence. """ if window_size < 3: raise ValueError("Specify window_size at least 3") wfd = FreqDist() wildfd = FreqDist() bfd = FreqDist() tfd = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3 in _itertools.combinations(window[1:], 2): wfd[w1] += 1 if w2 is None: continue bfd[(w1, w2)] += 1 if w3 is None: continue wildfd[(w1, w3)] += 1 tfd[(w1, w2, w3)] += 1 return cls(wfd, bfd, wildfd, tfd) def bigram_finder(self): """Constructs a bigram collocation finder with the bigram and unigram data from this finder. Note that this does not include any filtering applied to this finder. """ return BigramCollocationFinder(self.word_fd, self.bigram_fd) def score_ngram(self, score_fn, w1, w2, w3): """Returns the score for a given trigram using the given scoring function. """ n_all = self.N n_iii = self.ngram_fd[(w1, w2, w3)] if not n_iii: return n_iix = self.bigram_fd[(w1, w2)] n_ixi = self.wildcard_fd[(w1, w3)] n_xii = self.bigram_fd[(w2, w3)] n_ixx = self.word_fd[w1] n_xix = self.word_fd[w2] n_xxi = self.word_fd[w3] return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all) class QuadgramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of quadgram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 4 def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii): """Construct a QuadgramCollocationFinder, given FreqDists for appearances of words, bigrams, trigrams, two words with one word and two words between them, three words with a word between them in both variations. """ AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd) self.iii = iii self.ii = ii self.ixi = ixi self.ixxi = ixxi self.iixi = iixi self.ixii = ixii @classmethod def from_words(cls, words, window_size=4): if window_size < 4: raise ValueError("Specify window_size at least 4") ixxx = FreqDist() iiii = FreqDist() ii = FreqDist() iii = FreqDist() ixi = FreqDist() ixxi = FreqDist() iixi = FreqDist() ixii = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3, w4 in _itertools.combinations(window[1:], 3): ixxx[w1] += 1 if w2 is None: continue ii[(w1, w2)] += 1 if w3 is None: continue iii[(w1, w2, w3)] += 1 ixi[(w1, w3)] += 1 if w4 is None: continue iiii[(w1, w2, w3, w4)] += 1 ixxi[(w1, w4)] += 1 ixii[(w1, w3, w4)] += 1 iixi[(w1, w2, w4)] += 1 return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii) def score_ngram(self, score_fn, w1, w2, w3, w4): n_all = self.N n_iiii = self.ngram_fd[(w1, w2, w3, w4)] if not n_iiii: return n_iiix = self.iii[(w1, w2, w3)] n_xiii = self.iii[(w2, w3, w4)] n_iixi = self.iixi[(w1, w2, w4)] n_ixii = self.ixii[(w1, w3, w4)] n_iixx = self.ii[(w1, w2)] n_xxii = self.ii[(w3, w4)] n_xiix = self.ii[(w2, w3)] n_ixix = self.ixi[(w1, w3)] n_ixxi = self.ixxi[(w1, w4)] n_xixi = self.ixi[(w2, w4)] n_ixxx = self.word_fd[w1] n_xixx = self.word_fd[w2] n_xxix = self.word_fd[w3] n_xxxi = self.word_fd[w4] return score_fn( n_iiii, (n_iiix, n_iixi, n_ixii, n_xiii), (n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix), (n_ixxx, n_xixx, n_xxix, n_xxxi), n_all, ) def demo(scorer=None, compare_scorer=None): """Finds bigram collocations in the files of the WebText corpus.""" from nltk.metrics import ( BigramAssocMeasures, ranks_from_scores, spearman_correlation, ) if scorer is None: scorer = BigramAssocMeasures.likelihood_ratio if compare_scorer is None: compare_scorer = BigramAssocMeasures.raw_freq from nltk.corpus import stopwords, webtext ignored_words = stopwords.words("english") word_filter = lambda w: len(w) < 3 or w.lower() in ignored_words for file in webtext.fileids(): words = [word.lower() for word in webtext.words(file)] cf = BigramCollocationFinder.from_words(words) cf.apply_freq_filter(3) cf.apply_word_filter(word_filter) corr = spearman_correlation( ranks_from_scores(cf.score_ngrams(scorer)), ranks_from_scores(cf.score_ngrams(compare_scorer)), ) print(file) print("\t", [" ".join(tup) for tup in cf.nbest(scorer, 15)]) print(f"\t Correlation to {compare_scorer.__name__}: {corr:0.4f}") # Slows down loading too much # bigram_measures = BigramAssocMeasures() # trigram_measures = TrigramAssocMeasures() if __name__ == "__main__": import sys from nltk.metrics import BigramAssocMeasures try: scorer = eval("BigramAssocMeasures." + sys.argv[1]) except IndexError: scorer = None try: compare_scorer = eval("BigramAssocMeasures." + sys.argv[2]) except IndexError: compare_scorer = None demo(scorer, compare_scorer) __all__ = [ "BigramCollocationFinder", "TrigramCollocationFinder", "QuadgramCollocationFinder", ]
"""Removes candidate ngrams which have frequency less than min_freq.""" self._apply_filter(lambda ng, freq: freq < min_freq)
identifier_body
collocations.py
# Natural Language Toolkit: Collocations and Association Measures # # Copyright (C) 2001-2023 NLTK Project # Author: Joel Nothman <jnothman@student.usyd.edu.au> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT # """ Tools to identify collocations --- words that often appear consecutively --- within corpora. They may also be used to find other associations between word occurrences. See Manning and Schutze ch. 5 at https://nlp.stanford.edu/fsnlp/promo/colloc.pdf and the Text::NSP Perl package at http://ngram.sourceforge.net Finding collocations requires first calculating the frequencies of words and their appearance in the context of other words. Often the collection of words will then requiring filtering to only retain useful content terms. Each ngram of words may then be scored according to some association measure, in order to determine the relative likelihood of each ngram being a collocation. The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide these functionalities, dependent on being provided a function which scores a ngram given appropriate frequency counts. A number of standard association measures are provided in bigram_measures and trigram_measures. """ # Possible TODOs: # - consider the distinction between f(x,_) and f(x) and whether our # approximation is good enough for fragmented data, and mention it # - add a n-gram collocation finder with measures which only utilise n-gram # and unigram counts (raw_freq, pmi, student_t) import itertools as _itertools # these two unused imports are referenced in collocations.doctest from nltk.metrics import ( BigramAssocMeasures, ContingencyMeasures, QuadgramAssocMeasures, TrigramAssocMeasures, ) from nltk.metrics.spearman import ranks_from_scores, spearman_correlation from nltk.probability import FreqDist from nltk.util import ngrams class AbstractCollocationFinder: """ An abstract base class for collocation finders whose purpose is to collect collocation candidate frequencies, filter and rank them. As a minimum, collocation finders require the frequencies of each word in a corpus, and the joint frequency of word tuples. This data should be provided through nltk.probability.FreqDist objects or an identical interface. """ def __init__(self, word_fd, ngram_fd): self.word_fd = word_fd self.N = word_fd.N() self.ngram_fd = ngram_fd @classmethod def _build_new_documents( cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None ): """ Pad the document with the place holder according to the window_size """ padding = (pad_symbol,) * (window_size - 1) if pad_right: return _itertools.chain.from_iterable( _itertools.chain(doc, padding) for doc in documents ) if pad_left: return _itertools.chain.from_iterable( _itertools.chain(padding, doc) for doc in documents ) @classmethod def from_documents(cls, documents): """Constructs a collocation finder given a collection of documents, each of which is a list (or iterable) of tokens. """ # return cls.from_words(_itertools.chain(*documents)) return cls.from_words( cls._build_new_documents(documents, cls.default_ws, pad_right=True) ) @staticmethod def _ngram_freqdist(words, n): return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1)) def _apply_filter(self, fn=lambda ngram, freq: False): """Generic filter removes ngrams from the frequency distribution if the function returns True when passed an ngram tuple. """ tmp_ngram = FreqDist() for ngram, freq in self.ngram_fd.items(): if not fn(ngram, freq): tmp_ngram[ngram] = freq self.ngram_fd = tmp_ngram def apply_freq_filter(self, min_freq): """Removes candidate ngrams which have frequency less than min_freq.""" self._apply_filter(lambda ng, freq: freq < min_freq) def apply_ngram_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...) evaluates to True. """ self._apply_filter(lambda ng, f: fn(*ng)) def apply_word_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2), ...) evaluates to True. """ self._apply_filter(lambda ng, f: any(fn(w) for w in ng)) def _score_ngrams(self, score_fn): """Generates of (ngram, score) pairs as determined by the scoring function provided. """ for tup in self.ngram_fd: score = self.score_ngram(score_fn, *tup) if score is not None: yield tup, score def score_ngrams(self, score_fn): """Returns a sequence of (ngram, score) pairs ordered from highest to lowest score, as determined by the scoring function provided. """ return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0])) def nbest(self, score_fn, n): """Returns the top n ngrams when scored by the given function.""" return [p for p, s in self.score_ngrams(score_fn)[:n]] def above_score(self, score_fn, min_score): """Returns a sequence of ngrams, ordered by decreasing score, whose scores each exceed the given minimum score. """ for ngram, score in self.score_ngrams(score_fn): if score > min_score: yield ngram else: break class BigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of bigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 2 def __init__(self, word_fd, bigram_fd, window_size=2): """Construct a BigramCollocationFinder, given FreqDists for appearances of words and (possibly non-contiguous) bigrams. """ AbstractCollocationFinder.__init__(self, word_fd, bigram_fd) self.window_size = window_size @classmethod def from_words(cls, words, window_size=2): """Construct a BigramCollocationFinder for all bigrams in the given sequence. When window_size > 2, count non-contiguous bigrams, in the style of Church and Hanks's (1990) association ratio. """ wfd = FreqDist() bfd = FreqDist() if window_size < 2: raise ValueError("Specify window_size at least 2") for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue wfd[w1] += 1 for w2 in window[1:]: if w2 is not None: bfd[(w1, w2)] += 1 return cls(wfd, bfd, window_size=window_size) def score_ngram(self, score_fn, w1, w2): """Returns the score for a given bigram using the given scoring function. Following Church and Hanks (1990), counts are scaled by a factor of 1/(window_size - 1). """ n_all = self.N n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0) if not n_ii:
n_ix = self.word_fd[w1] n_xi = self.word_fd[w2] return score_fn(n_ii, (n_ix, n_xi), n_all) class TrigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of trigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 3 def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): """Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams. """ AbstractCollocationFinder.__init__(self, word_fd, trigram_fd) self.wildcard_fd = wildcard_fd self.bigram_fd = bigram_fd @classmethod def from_words(cls, words, window_size=3): """Construct a TrigramCollocationFinder for all trigrams in the given sequence. """ if window_size < 3: raise ValueError("Specify window_size at least 3") wfd = FreqDist() wildfd = FreqDist() bfd = FreqDist() tfd = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3 in _itertools.combinations(window[1:], 2): wfd[w1] += 1 if w2 is None: continue bfd[(w1, w2)] += 1 if w3 is None: continue wildfd[(w1, w3)] += 1 tfd[(w1, w2, w3)] += 1 return cls(wfd, bfd, wildfd, tfd) def bigram_finder(self): """Constructs a bigram collocation finder with the bigram and unigram data from this finder. Note that this does not include any filtering applied to this finder. """ return BigramCollocationFinder(self.word_fd, self.bigram_fd) def score_ngram(self, score_fn, w1, w2, w3): """Returns the score for a given trigram using the given scoring function. """ n_all = self.N n_iii = self.ngram_fd[(w1, w2, w3)] if not n_iii: return n_iix = self.bigram_fd[(w1, w2)] n_ixi = self.wildcard_fd[(w1, w3)] n_xii = self.bigram_fd[(w2, w3)] n_ixx = self.word_fd[w1] n_xix = self.word_fd[w2] n_xxi = self.word_fd[w3] return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all) class QuadgramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of quadgram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 4 def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii): """Construct a QuadgramCollocationFinder, given FreqDists for appearances of words, bigrams, trigrams, two words with one word and two words between them, three words with a word between them in both variations. """ AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd) self.iii = iii self.ii = ii self.ixi = ixi self.ixxi = ixxi self.iixi = iixi self.ixii = ixii @classmethod def from_words(cls, words, window_size=4): if window_size < 4: raise ValueError("Specify window_size at least 4") ixxx = FreqDist() iiii = FreqDist() ii = FreqDist() iii = FreqDist() ixi = FreqDist() ixxi = FreqDist() iixi = FreqDist() ixii = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3, w4 in _itertools.combinations(window[1:], 3): ixxx[w1] += 1 if w2 is None: continue ii[(w1, w2)] += 1 if w3 is None: continue iii[(w1, w2, w3)] += 1 ixi[(w1, w3)] += 1 if w4 is None: continue iiii[(w1, w2, w3, w4)] += 1 ixxi[(w1, w4)] += 1 ixii[(w1, w3, w4)] += 1 iixi[(w1, w2, w4)] += 1 return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii) def score_ngram(self, score_fn, w1, w2, w3, w4): n_all = self.N n_iiii = self.ngram_fd[(w1, w2, w3, w4)] if not n_iiii: return n_iiix = self.iii[(w1, w2, w3)] n_xiii = self.iii[(w2, w3, w4)] n_iixi = self.iixi[(w1, w2, w4)] n_ixii = self.ixii[(w1, w3, w4)] n_iixx = self.ii[(w1, w2)] n_xxii = self.ii[(w3, w4)] n_xiix = self.ii[(w2, w3)] n_ixix = self.ixi[(w1, w3)] n_ixxi = self.ixxi[(w1, w4)] n_xixi = self.ixi[(w2, w4)] n_ixxx = self.word_fd[w1] n_xixx = self.word_fd[w2] n_xxix = self.word_fd[w3] n_xxxi = self.word_fd[w4] return score_fn( n_iiii, (n_iiix, n_iixi, n_ixii, n_xiii), (n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix), (n_ixxx, n_xixx, n_xxix, n_xxxi), n_all, ) def demo(scorer=None, compare_scorer=None): """Finds bigram collocations in the files of the WebText corpus.""" from nltk.metrics import ( BigramAssocMeasures, ranks_from_scores, spearman_correlation, ) if scorer is None: scorer = BigramAssocMeasures.likelihood_ratio if compare_scorer is None: compare_scorer = BigramAssocMeasures.raw_freq from nltk.corpus import stopwords, webtext ignored_words = stopwords.words("english") word_filter = lambda w: len(w) < 3 or w.lower() in ignored_words for file in webtext.fileids(): words = [word.lower() for word in webtext.words(file)] cf = BigramCollocationFinder.from_words(words) cf.apply_freq_filter(3) cf.apply_word_filter(word_filter) corr = spearman_correlation( ranks_from_scores(cf.score_ngrams(scorer)), ranks_from_scores(cf.score_ngrams(compare_scorer)), ) print(file) print("\t", [" ".join(tup) for tup in cf.nbest(scorer, 15)]) print(f"\t Correlation to {compare_scorer.__name__}: {corr:0.4f}") # Slows down loading too much # bigram_measures = BigramAssocMeasures() # trigram_measures = TrigramAssocMeasures() if __name__ == "__main__": import sys from nltk.metrics import BigramAssocMeasures try: scorer = eval("BigramAssocMeasures." + sys.argv[1]) except IndexError: scorer = None try: compare_scorer = eval("BigramAssocMeasures." + sys.argv[2]) except IndexError: compare_scorer = None demo(scorer, compare_scorer) __all__ = [ "BigramCollocationFinder", "TrigramCollocationFinder", "QuadgramCollocationFinder", ]
return
conditional_block
collocations.py
# Natural Language Toolkit: Collocations and Association Measures # # Copyright (C) 2001-2023 NLTK Project # Author: Joel Nothman <jnothman@student.usyd.edu.au> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT # """ Tools to identify collocations --- words that often appear consecutively --- within corpora. They may also be used to find other associations between word occurrences. See Manning and Schutze ch. 5 at https://nlp.stanford.edu/fsnlp/promo/colloc.pdf and the Text::NSP Perl package at http://ngram.sourceforge.net Finding collocations requires first calculating the frequencies of words and their appearance in the context of other words. Often the collection of words will then requiring filtering to only retain useful content terms. Each ngram of words may then be scored according to some association measure, in order to determine the relative likelihood of each ngram being a collocation. The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide these functionalities, dependent on being provided a function which scores a ngram given appropriate frequency counts. A number of standard association measures are provided in bigram_measures and trigram_measures. """ # Possible TODOs: # - consider the distinction between f(x,_) and f(x) and whether our # approximation is good enough for fragmented data, and mention it # - add a n-gram collocation finder with measures which only utilise n-gram # and unigram counts (raw_freq, pmi, student_t) import itertools as _itertools # these two unused imports are referenced in collocations.doctest from nltk.metrics import ( BigramAssocMeasures, ContingencyMeasures, QuadgramAssocMeasures, TrigramAssocMeasures, ) from nltk.metrics.spearman import ranks_from_scores, spearman_correlation from nltk.probability import FreqDist from nltk.util import ngrams class AbstractCollocationFinder: """ An abstract base class for collocation finders whose purpose is to collect collocation candidate frequencies, filter and rank them. As a minimum, collocation finders require the frequencies of each word in a corpus, and the joint frequency of word tuples. This data should be provided through nltk.probability.FreqDist objects or an identical interface. """ def __init__(self, word_fd, ngram_fd): self.word_fd = word_fd self.N = word_fd.N() self.ngram_fd = ngram_fd @classmethod def _build_new_documents( cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None ): """ Pad the document with the place holder according to the window_size """ padding = (pad_symbol,) * (window_size - 1) if pad_right: return _itertools.chain.from_iterable( _itertools.chain(doc, padding) for doc in documents ) if pad_left: return _itertools.chain.from_iterable( _itertools.chain(padding, doc) for doc in documents ) @classmethod def from_documents(cls, documents): """Constructs a collocation finder given a collection of documents, each of which is a list (or iterable) of tokens. """ # return cls.from_words(_itertools.chain(*documents)) return cls.from_words( cls._build_new_documents(documents, cls.default_ws, pad_right=True) ) @staticmethod def _ngram_freqdist(words, n): return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1)) def _apply_filter(self, fn=lambda ngram, freq: False): """Generic filter removes ngrams from the frequency distribution if the function returns True when passed an ngram tuple. """ tmp_ngram = FreqDist() for ngram, freq in self.ngram_fd.items(): if not fn(ngram, freq): tmp_ngram[ngram] = freq self.ngram_fd = tmp_ngram def apply_freq_filter(self, min_freq): """Removes candidate ngrams which have frequency less than min_freq.""" self._apply_filter(lambda ng, freq: freq < min_freq) def apply_ngram_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...) evaluates to True. """ self._apply_filter(lambda ng, f: fn(*ng)) def apply_word_filter(self, fn): """Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2), ...) evaluates to True. """ self._apply_filter(lambda ng, f: any(fn(w) for w in ng)) def _score_ngrams(self, score_fn): """Generates of (ngram, score) pairs as determined by the scoring function provided. """ for tup in self.ngram_fd: score = self.score_ngram(score_fn, *tup) if score is not None: yield tup, score def score_ngrams(self, score_fn): """Returns a sequence of (ngram, score) pairs ordered from highest to lowest score, as determined by the scoring function provided. """ return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0])) def nbest(self, score_fn, n): """Returns the top n ngrams when scored by the given function.""" return [p for p, s in self.score_ngrams(score_fn)[:n]] def above_score(self, score_fn, min_score): """Returns a sequence of ngrams, ordered by decreasing score, whose scores each exceed the given minimum score. """ for ngram, score in self.score_ngrams(score_fn): if score > min_score: yield ngram else: break class BigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of bigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 2 def __init__(self, word_fd, bigram_fd, window_size=2): """Construct a BigramCollocationFinder, given FreqDists for appearances of words and (possibly non-contiguous) bigrams. """ AbstractCollocationFinder.__init__(self, word_fd, bigram_fd) self.window_size = window_size @classmethod def from_words(cls, words, window_size=2): """Construct a BigramCollocationFinder for all bigrams in the given sequence. When window_size > 2, count non-contiguous bigrams, in the style of Church and Hanks's (1990) association ratio. """ wfd = FreqDist() bfd = FreqDist() if window_size < 2: raise ValueError("Specify window_size at least 2") for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue wfd[w1] += 1 for w2 in window[1:]: if w2 is not None: bfd[(w1, w2)] += 1 return cls(wfd, bfd, window_size=window_size) def score_ngram(self, score_fn, w1, w2): """Returns the score for a given bigram using the given scoring function. Following Church and Hanks (1990), counts are scaled by a factor of 1/(window_size - 1). """ n_all = self.N n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0) if not n_ii: return n_ix = self.word_fd[w1] n_xi = self.word_fd[w2] return score_fn(n_ii, (n_ix, n_xi), n_all) class TrigramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of trigram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 3 def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): """Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams. """ AbstractCollocationFinder.__init__(self, word_fd, trigram_fd) self.wildcard_fd = wildcard_fd self.bigram_fd = bigram_fd @classmethod def from_words(cls, words, window_size=3): """Construct a TrigramCollocationFinder for all trigrams in the given sequence. """ if window_size < 3: raise ValueError("Specify window_size at least 3") wfd = FreqDist() wildfd = FreqDist() bfd = FreqDist() tfd = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3 in _itertools.combinations(window[1:], 2): wfd[w1] += 1 if w2 is None: continue bfd[(w1, w2)] += 1 if w3 is None: continue wildfd[(w1, w3)] += 1 tfd[(w1, w2, w3)] += 1 return cls(wfd, bfd, wildfd, tfd) def bigram_finder(self): """Constructs a bigram collocation finder with the bigram and unigram data from this finder. Note that this does not include any filtering applied to this finder. """ return BigramCollocationFinder(self.word_fd, self.bigram_fd) def score_ngram(self, score_fn, w1, w2, w3): """Returns the score for a given trigram using the given scoring function. """ n_all = self.N n_iii = self.ngram_fd[(w1, w2, w3)] if not n_iii: return n_iix = self.bigram_fd[(w1, w2)] n_ixi = self.wildcard_fd[(w1, w3)] n_xii = self.bigram_fd[(w2, w3)] n_ixx = self.word_fd[w1] n_xix = self.word_fd[w2] n_xxi = self.word_fd[w3] return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all) class QuadgramCollocationFinder(AbstractCollocationFinder): """A tool for the finding and ranking of quadgram collocations or other association measures. It is often useful to use from_words() rather than constructing an instance directly. """ default_ws = 4 def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii): """Construct a QuadgramCollocationFinder, given FreqDists for appearances of words, bigrams, trigrams, two words with one word and two words between them, three words with a word between them in both variations. """ AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd) self.iii = iii self.ii = ii self.ixi = ixi self.ixxi = ixxi self.iixi = iixi self.ixii = ixii @classmethod def from_words(cls, words, window_size=4): if window_size < 4: raise ValueError("Specify window_size at least 4") ixxx = FreqDist() iiii = FreqDist() ii = FreqDist() iii = FreqDist() ixi = FreqDist() ixxi = FreqDist() iixi = FreqDist() ixii = FreqDist() for window in ngrams(words, window_size, pad_right=True): w1 = window[0] if w1 is None: continue for w2, w3, w4 in _itertools.combinations(window[1:], 3): ixxx[w1] += 1 if w2 is None: continue ii[(w1, w2)] += 1 if w3 is None: continue iii[(w1, w2, w3)] += 1 ixi[(w1, w3)] += 1 if w4 is None: continue iiii[(w1, w2, w3, w4)] += 1 ixxi[(w1, w4)] += 1 ixii[(w1, w3, w4)] += 1 iixi[(w1, w2, w4)] += 1 return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii) def score_ngram(self, score_fn, w1, w2, w3, w4): n_all = self.N n_iiii = self.ngram_fd[(w1, w2, w3, w4)] if not n_iiii: return n_iiix = self.iii[(w1, w2, w3)] n_xiii = self.iii[(w2, w3, w4)] n_iixi = self.iixi[(w1, w2, w4)] n_ixii = self.ixii[(w1, w3, w4)] n_iixx = self.ii[(w1, w2)] n_xxii = self.ii[(w3, w4)] n_xiix = self.ii[(w2, w3)] n_ixix = self.ixi[(w1, w3)] n_ixxi = self.ixxi[(w1, w4)] n_xixi = self.ixi[(w2, w4)] n_ixxx = self.word_fd[w1] n_xixx = self.word_fd[w2] n_xxix = self.word_fd[w3] n_xxxi = self.word_fd[w4] return score_fn( n_iiii, (n_iiix, n_iixi, n_ixii, n_xiii), (n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix), (n_ixxx, n_xixx, n_xxix, n_xxxi), n_all, ) def demo(scorer=None, compare_scorer=None): """Finds bigram collocations in the files of the WebText corpus.""" from nltk.metrics import ( BigramAssocMeasures, ranks_from_scores, spearman_correlation, ) if scorer is None: scorer = BigramAssocMeasures.likelihood_ratio if compare_scorer is None:
ignored_words = stopwords.words("english") word_filter = lambda w: len(w) < 3 or w.lower() in ignored_words for file in webtext.fileids(): words = [word.lower() for word in webtext.words(file)] cf = BigramCollocationFinder.from_words(words) cf.apply_freq_filter(3) cf.apply_word_filter(word_filter) corr = spearman_correlation( ranks_from_scores(cf.score_ngrams(scorer)), ranks_from_scores(cf.score_ngrams(compare_scorer)), ) print(file) print("\t", [" ".join(tup) for tup in cf.nbest(scorer, 15)]) print(f"\t Correlation to {compare_scorer.__name__}: {corr:0.4f}") # Slows down loading too much # bigram_measures = BigramAssocMeasures() # trigram_measures = TrigramAssocMeasures() if __name__ == "__main__": import sys from nltk.metrics import BigramAssocMeasures try: scorer = eval("BigramAssocMeasures." + sys.argv[1]) except IndexError: scorer = None try: compare_scorer = eval("BigramAssocMeasures." + sys.argv[2]) except IndexError: compare_scorer = None demo(scorer, compare_scorer) __all__ = [ "BigramCollocationFinder", "TrigramCollocationFinder", "QuadgramCollocationFinder", ]
compare_scorer = BigramAssocMeasures.raw_freq from nltk.corpus import stopwords, webtext
random_line_split
decode.rs
/* Copyright 2013 10gen Inc. * * 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. */ use std::str::from_bytes; use std::int::range; use std::cast::transmute; use encode::*; use tools::stream::*; static L_END: bool = true; //Format codes static DOUBLE: u8 = 0x01; static STRING: u8 = 0x02; static EMBED: u8 = 0x03; static ARRAY: u8 = 0x04; static BINARY: u8 = 0x05; static OBJID: u8 = 0x07; static BOOL: u8 = 0x08; static UTCDATE: u8 = 0x09; static NULL: u8 = 0x0A; static REGEX: u8 = 0x0B; static DBREF: u8 = 0x0C; static JSCRIPT: u8 = 0x0D; static JSCOPE: u8 = 0x0F; static INT32: u8 = 0x10; static TSTAMP: u8 = 0x11; static INT64: u8 = 0x12; static MINKEY: u8 = 0xFF; static MAXKEY: u8 = 0x7F; ///Parser object for BSON. T is constrained to Stream<u8>. pub struct BsonParser<T> { stream: T } ///Collects up to 8 bytes in order as a u64. priv fn bytesum(bytes: &[u8]) -> u64 { let mut i = 0; let mut ret: u64 = 0; for bytes.iter().advance |&byte| { ret |= (byte as u64) >> (8 * i); i += 1; } ret } impl<T:Stream<u8>> BsonParser<T> { ///Parse a byte stream into a BsonDocument. Returns an error string on parse failure. ///Initializing a BsonParser and calling document() will fully convert a ~[u8] ///into a BsonDocument if it was formatted correctly. pub fn document(&mut self) -> Result<BsonDocument,~str> { let size = bytesum(self.stream.aggregate(4)) as i32; let mut elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); self.stream.pass(1); let mut ret = BsonDocument::new(); while elemcode != None { let key = self.cstring(); let val: Document = match elemcode { Some(DOUBLE) => self._double(), Some(STRING) => self._string(), Some(EMBED) => { let doc = self._embed(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(ARRAY) => { let doc = self._array(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(BINARY) => self._binary(), Some(OBJID) => ObjectId(self.stream.aggregate(12)), Some(BOOL) => self._bool(), Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64), Some(NULL) => Null, Some(REGEX) => self._regex(), Some(DBREF) => { let doc = self._dbref(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCRIPT) => { let doc = self._jscript(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCOPE) => { let doc = self._jscope(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32), Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32, bytesum(self.stream.aggregate(4)) as u32), Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64), Some(MINKEY) => MinKey, Some(MAXKEY) => MaxKey, _ => return Err(~"an invalid element code was found") }; ret.put(key, val); elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); if self.stream.has_next() { self.stream.pass(1); } } ret.size = size; Ok(ret) } ///Parse a string without denoting its length. Mainly for keys. fn cstring(&mut self) -> ~str { let is_0: &fn(&u8) -> bool = |&x| x == 0x00; let s = from_bytes(self.stream.until(is_0)); self.stream.pass(1); s } ///Parse a double. fn _double(&mut self) -> Document { let mut u: u64 = 0; for range(0,8) |i| { //TODO: how will this hold up on big-endian architectures? u |= (*self.stream.first() as u64 << ((8 * i))); self.stream.pass(1); } let v: &f64 = unsafe { transmute(&u) }; Double(*v) } ///Parse a string with length. fn _string(&mut self) -> Document { self.stream.pass(4); //skip length let v = self.cstring(); UString(v) } ///Parse an embedded object. May fail. fn _embed(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Embedded(~s))); } ///Parse an embedded array. May fail. fn _array(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Array(~s))); } ///Parse generic binary data. fn _binary(&mut self) -> Document { let count = bytesum(self.stream.aggregate(4)); let subtype = *(self.stream.first()); self.stream.pass(1); let data = self.stream.aggregate(count as uint); Binary(subtype, data) } ///Parse a boolean. fn _bool(&mut self) -> Document { let ret = (*self.stream.first()) as bool; self.stream.pass(1); Bool(ret) } ///Parse a regex. fn _regex(&mut self) -> Document { let s1 = self.cstring(); let s2 = self.cstring(); Regex(s1, s2) } fn _dbref(&mut self) -> Result<Document, ~str> { let s = match self._string() { UString(rs) => rs, _ => return Err(~"invalid string found in dbref") }; let d = self.stream.aggregate(12); Ok(DBRef(s, ~ObjectId(d))) }
fn _jscript(&mut self) -> Result<Document, ~str> { let s = self._string(); //using this to avoid irrefutable pattern error match s { UString(s) => Ok(JScript(s)), _ => Err(~"invalid string found in javascript") } } ///Parse a scoped javascript object. fn _jscope(&mut self) -> Result<Document,~str> { self.stream.pass(4); let s = self.cstring(); let doc = self.document(); return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d))); } ///Create a new parser with a given stream. pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } } } ///Standalone decode binding. ///This is equivalent to initializing a parser and calling document(). pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> { let mut parser = BsonParser::new(b); parser.document() } #[cfg(test)] mod tests { use super::*; use encode::*; use extra::test::BenchHarness; #[test] fn test_decode_size() { let doc = decode(~[10,0,0,0,10,100,100,100,0]); assert_eq!(doc.unwrap().size, 10); } #[test] fn test_cstring_decode() { let stream: ~[u8] = ~[104,101,108,108,111,0]; let mut parser = BsonParser::new(stream); assert_eq!(parser.cstring(), ~"hello"); } #[test] fn test_double_decode() { let stream: ~[u8] = ~[110,134,27,240,249,33,9,64]; let mut parser = BsonParser::new(stream); let d = parser._double(); match d { Double(d2) => { assert!(d2.approx_eq(&3.14159f64)); } _ => fail!("failed in a test case; how did I get here?") } } #[test] fn test_document_decode() { let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0]; let mut parser1 = BsonParser::new(stream1); let mut doc1 = BsonDocument::new(); doc1.put(~"foo", Bool(true)); assert_eq!(parser1.document().unwrap(), doc1); let stream2: ~[u8] = ~[45,0,0,0,4,102,111,111,0,22,0,0,0,2,48,0, 6,0,0,0,104,101,108,108,111,0,8,49,0,0, 0,2,98,97,122,0,4,0,0,0,113,117,120,0,0]; let mut inside = BsonDocument::new(); inside.put_all(~[(~"0", UString(~"hello")), (~"1", Bool(false))]); let mut doc2 = BsonDocument::new(); doc2.put_all(~[(~"foo", Array(~inside.clone())), (~"baz", UString(~"qux"))]); assert_eq!(decode(stream2).unwrap(), doc2); } #[test] fn test_binary_decode() { let stream: ~[u8] = ~[6,0,0,0,0,1,2,3,4,5,6]; let mut parser = BsonParser::new(stream); assert_eq!(parser._binary(), Binary(0, ~[1,2,3,4,5,6])); } #[test] fn test_dbref_encode() { let mut doc = BsonDocument::new(); doc.put(~"foo", DBRef(~"bar", ~ObjectId(~[0u8,1,2,3,4,5,6,7,8,9,10,11]))); let stream: ~[u8] = ~[30,0,0,0,12,102,111,111,0,4,0,0,0,98,97,114,0,0,1,2,3,4,5,6,7,8,9,10,11,0]; assert_eq!(decode(stream).unwrap(), doc) } //TODO: get bson strings of torture-test objects #[bench] fn bench_basic_obj_decode(b: &mut BenchHarness) { do b.iter { let stream: ~[u8] = ~[45,0,0,0,4,102,111, 111,0,22,0,0,0,2,48,0,6,0,0,0,104,101,108, 108,111,0,8,49,0,0,0,2,98,97,122,0,4,0,0,0, 113,117,120,0,0]; decode(stream); } } }
///Parse a javascript object.
random_line_split
decode.rs
/* Copyright 2013 10gen Inc. * * 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. */ use std::str::from_bytes; use std::int::range; use std::cast::transmute; use encode::*; use tools::stream::*; static L_END: bool = true; //Format codes static DOUBLE: u8 = 0x01; static STRING: u8 = 0x02; static EMBED: u8 = 0x03; static ARRAY: u8 = 0x04; static BINARY: u8 = 0x05; static OBJID: u8 = 0x07; static BOOL: u8 = 0x08; static UTCDATE: u8 = 0x09; static NULL: u8 = 0x0A; static REGEX: u8 = 0x0B; static DBREF: u8 = 0x0C; static JSCRIPT: u8 = 0x0D; static JSCOPE: u8 = 0x0F; static INT32: u8 = 0x10; static TSTAMP: u8 = 0x11; static INT64: u8 = 0x12; static MINKEY: u8 = 0xFF; static MAXKEY: u8 = 0x7F; ///Parser object for BSON. T is constrained to Stream<u8>. pub struct BsonParser<T> { stream: T } ///Collects up to 8 bytes in order as a u64. priv fn bytesum(bytes: &[u8]) -> u64 { let mut i = 0; let mut ret: u64 = 0; for bytes.iter().advance |&byte| { ret |= (byte as u64) >> (8 * i); i += 1; } ret } impl<T:Stream<u8>> BsonParser<T> { ///Parse a byte stream into a BsonDocument. Returns an error string on parse failure. ///Initializing a BsonParser and calling document() will fully convert a ~[u8] ///into a BsonDocument if it was formatted correctly. pub fn document(&mut self) -> Result<BsonDocument,~str> { let size = bytesum(self.stream.aggregate(4)) as i32; let mut elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); self.stream.pass(1); let mut ret = BsonDocument::new(); while elemcode != None { let key = self.cstring(); let val: Document = match elemcode { Some(DOUBLE) => self._double(), Some(STRING) => self._string(), Some(EMBED) => { let doc = self._embed(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(ARRAY) => { let doc = self._array(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(BINARY) => self._binary(), Some(OBJID) => ObjectId(self.stream.aggregate(12)), Some(BOOL) => self._bool(), Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64), Some(NULL) => Null, Some(REGEX) => self._regex(), Some(DBREF) => { let doc = self._dbref(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCRIPT) => { let doc = self._jscript(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCOPE) => { let doc = self._jscope(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32), Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32, bytesum(self.stream.aggregate(4)) as u32), Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64), Some(MINKEY) => MinKey, Some(MAXKEY) => MaxKey, _ => return Err(~"an invalid element code was found") }; ret.put(key, val); elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); if self.stream.has_next() { self.stream.pass(1); } } ret.size = size; Ok(ret) } ///Parse a string without denoting its length. Mainly for keys. fn cstring(&mut self) -> ~str { let is_0: &fn(&u8) -> bool = |&x| x == 0x00; let s = from_bytes(self.stream.until(is_0)); self.stream.pass(1); s } ///Parse a double. fn _double(&mut self) -> Document { let mut u: u64 = 0; for range(0,8) |i| { //TODO: how will this hold up on big-endian architectures? u |= (*self.stream.first() as u64 << ((8 * i))); self.stream.pass(1); } let v: &f64 = unsafe { transmute(&u) }; Double(*v) } ///Parse a string with length. fn _string(&mut self) -> Document { self.stream.pass(4); //skip length let v = self.cstring(); UString(v) } ///Parse an embedded object. May fail. fn _embed(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Embedded(~s))); } ///Parse an embedded array. May fail. fn _array(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Array(~s))); } ///Parse generic binary data. fn _binary(&mut self) -> Document { let count = bytesum(self.stream.aggregate(4)); let subtype = *(self.stream.first()); self.stream.pass(1); let data = self.stream.aggregate(count as uint); Binary(subtype, data) } ///Parse a boolean. fn _bool(&mut self) -> Document { let ret = (*self.stream.first()) as bool; self.stream.pass(1); Bool(ret) } ///Parse a regex. fn _regex(&mut self) -> Document { let s1 = self.cstring(); let s2 = self.cstring(); Regex(s1, s2) } fn _dbref(&mut self) -> Result<Document, ~str>
///Parse a javascript object. fn _jscript(&mut self) -> Result<Document, ~str> { let s = self._string(); //using this to avoid irrefutable pattern error match s { UString(s) => Ok(JScript(s)), _ => Err(~"invalid string found in javascript") } } ///Parse a scoped javascript object. fn _jscope(&mut self) -> Result<Document,~str> { self.stream.pass(4); let s = self.cstring(); let doc = self.document(); return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d))); } ///Create a new parser with a given stream. pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } } } ///Standalone decode binding. ///This is equivalent to initializing a parser and calling document(). pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> { let mut parser = BsonParser::new(b); parser.document() } #[cfg(test)] mod tests { use super::*; use encode::*; use extra::test::BenchHarness; #[test] fn test_decode_size() { let doc = decode(~[10,0,0,0,10,100,100,100,0]); assert_eq!(doc.unwrap().size, 10); } #[test] fn test_cstring_decode() { let stream: ~[u8] = ~[104,101,108,108,111,0]; let mut parser = BsonParser::new(stream); assert_eq!(parser.cstring(), ~"hello"); } #[test] fn test_double_decode() { let stream: ~[u8] = ~[110,134,27,240,249,33,9,64]; let mut parser = BsonParser::new(stream); let d = parser._double(); match d { Double(d2) => { assert!(d2.approx_eq(&3.14159f64)); } _ => fail!("failed in a test case; how did I get here?") } } #[test] fn test_document_decode() { let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0]; let mut parser1 = BsonParser::new(stream1); let mut doc1 = BsonDocument::new(); doc1.put(~"foo", Bool(true)); assert_eq!(parser1.document().unwrap(), doc1); let stream2: ~[u8] = ~[45,0,0,0,4,102,111,111,0,22,0,0,0,2,48,0, 6,0,0,0,104,101,108,108,111,0,8,49,0,0, 0,2,98,97,122,0,4,0,0,0,113,117,120,0,0]; let mut inside = BsonDocument::new(); inside.put_all(~[(~"0", UString(~"hello")), (~"1", Bool(false))]); let mut doc2 = BsonDocument::new(); doc2.put_all(~[(~"foo", Array(~inside.clone())), (~"baz", UString(~"qux"))]); assert_eq!(decode(stream2).unwrap(), doc2); } #[test] fn test_binary_decode() { let stream: ~[u8] = ~[6,0,0,0,0,1,2,3,4,5,6]; let mut parser = BsonParser::new(stream); assert_eq!(parser._binary(), Binary(0, ~[1,2,3,4,5,6])); } #[test] fn test_dbref_encode() { let mut doc = BsonDocument::new(); doc.put(~"foo", DBRef(~"bar", ~ObjectId(~[0u8,1,2,3,4,5,6,7,8,9,10,11]))); let stream: ~[u8] = ~[30,0,0,0,12,102,111,111,0,4,0,0,0,98,97,114,0,0,1,2,3,4,5,6,7,8,9,10,11,0]; assert_eq!(decode(stream).unwrap(), doc) } //TODO: get bson strings of torture-test objects #[bench] fn bench_basic_obj_decode(b: &mut BenchHarness) { do b.iter { let stream: ~[u8] = ~[45,0,0,0,4,102,111, 111,0,22,0,0,0,2,48,0,6,0,0,0,104,101,108, 108,111,0,8,49,0,0,0,2,98,97,122,0,4,0,0,0, 113,117,120,0,0]; decode(stream); } } }
{ let s = match self._string() { UString(rs) => rs, _ => return Err(~"invalid string found in dbref") }; let d = self.stream.aggregate(12); Ok(DBRef(s, ~ObjectId(d))) }
identifier_body
decode.rs
/* Copyright 2013 10gen Inc. * * 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. */ use std::str::from_bytes; use std::int::range; use std::cast::transmute; use encode::*; use tools::stream::*; static L_END: bool = true; //Format codes static DOUBLE: u8 = 0x01; static STRING: u8 = 0x02; static EMBED: u8 = 0x03; static ARRAY: u8 = 0x04; static BINARY: u8 = 0x05; static OBJID: u8 = 0x07; static BOOL: u8 = 0x08; static UTCDATE: u8 = 0x09; static NULL: u8 = 0x0A; static REGEX: u8 = 0x0B; static DBREF: u8 = 0x0C; static JSCRIPT: u8 = 0x0D; static JSCOPE: u8 = 0x0F; static INT32: u8 = 0x10; static TSTAMP: u8 = 0x11; static INT64: u8 = 0x12; static MINKEY: u8 = 0xFF; static MAXKEY: u8 = 0x7F; ///Parser object for BSON. T is constrained to Stream<u8>. pub struct BsonParser<T> { stream: T } ///Collects up to 8 bytes in order as a u64. priv fn bytesum(bytes: &[u8]) -> u64 { let mut i = 0; let mut ret: u64 = 0; for bytes.iter().advance |&byte| { ret |= (byte as u64) >> (8 * i); i += 1; } ret } impl<T:Stream<u8>> BsonParser<T> { ///Parse a byte stream into a BsonDocument. Returns an error string on parse failure. ///Initializing a BsonParser and calling document() will fully convert a ~[u8] ///into a BsonDocument if it was formatted correctly. pub fn document(&mut self) -> Result<BsonDocument,~str> { let size = bytesum(self.stream.aggregate(4)) as i32; let mut elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); self.stream.pass(1); let mut ret = BsonDocument::new(); while elemcode != None { let key = self.cstring(); let val: Document = match elemcode { Some(DOUBLE) => self._double(), Some(STRING) => self._string(), Some(EMBED) => { let doc = self._embed(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(ARRAY) => { let doc = self._array(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(BINARY) => self._binary(), Some(OBJID) => ObjectId(self.stream.aggregate(12)), Some(BOOL) => self._bool(), Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64), Some(NULL) => Null, Some(REGEX) => self._regex(), Some(DBREF) => { let doc = self._dbref(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCRIPT) => { let doc = self._jscript(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(JSCOPE) => { let doc = self._jscope(); match doc { Ok(d) => d, Err(e) => return Err(e) } } Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32), Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32, bytesum(self.stream.aggregate(4)) as u32), Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64), Some(MINKEY) => MinKey, Some(MAXKEY) => MaxKey, _ => return Err(~"an invalid element code was found") }; ret.put(key, val); elemcode = self.stream.expect(&[ DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID, BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE, INT32,TSTAMP,INT64,MINKEY,MAXKEY]); if self.stream.has_next() { self.stream.pass(1); } } ret.size = size; Ok(ret) } ///Parse a string without denoting its length. Mainly for keys. fn cstring(&mut self) -> ~str { let is_0: &fn(&u8) -> bool = |&x| x == 0x00; let s = from_bytes(self.stream.until(is_0)); self.stream.pass(1); s } ///Parse a double. fn _double(&mut self) -> Document { let mut u: u64 = 0; for range(0,8) |i| { //TODO: how will this hold up on big-endian architectures? u |= (*self.stream.first() as u64 << ((8 * i))); self.stream.pass(1); } let v: &f64 = unsafe { transmute(&u) }; Double(*v) } ///Parse a string with length. fn _string(&mut self) -> Document { self.stream.pass(4); //skip length let v = self.cstring(); UString(v) } ///Parse an embedded object. May fail. fn _embed(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Embedded(~s))); } ///Parse an embedded array. May fail. fn _array(&mut self) -> Result<Document,~str> { return self.document().chain(|s| Ok(Array(~s))); } ///Parse generic binary data. fn _binary(&mut self) -> Document { let count = bytesum(self.stream.aggregate(4)); let subtype = *(self.stream.first()); self.stream.pass(1); let data = self.stream.aggregate(count as uint); Binary(subtype, data) } ///Parse a boolean. fn _bool(&mut self) -> Document { let ret = (*self.stream.first()) as bool; self.stream.pass(1); Bool(ret) } ///Parse a regex. fn _regex(&mut self) -> Document { let s1 = self.cstring(); let s2 = self.cstring(); Regex(s1, s2) } fn _dbref(&mut self) -> Result<Document, ~str> { let s = match self._string() { UString(rs) => rs, _ => return Err(~"invalid string found in dbref") }; let d = self.stream.aggregate(12); Ok(DBRef(s, ~ObjectId(d))) } ///Parse a javascript object. fn _jscript(&mut self) -> Result<Document, ~str> { let s = self._string(); //using this to avoid irrefutable pattern error match s { UString(s) => Ok(JScript(s)), _ => Err(~"invalid string found in javascript") } } ///Parse a scoped javascript object. fn _jscope(&mut self) -> Result<Document,~str> { self.stream.pass(4); let s = self.cstring(); let doc = self.document(); return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d))); } ///Create a new parser with a given stream. pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } } } ///Standalone decode binding. ///This is equivalent to initializing a parser and calling document(). pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> { let mut parser = BsonParser::new(b); parser.document() } #[cfg(test)] mod tests { use super::*; use encode::*; use extra::test::BenchHarness; #[test] fn test_decode_size() { let doc = decode(~[10,0,0,0,10,100,100,100,0]); assert_eq!(doc.unwrap().size, 10); } #[test] fn test_cstring_decode() { let stream: ~[u8] = ~[104,101,108,108,111,0]; let mut parser = BsonParser::new(stream); assert_eq!(parser.cstring(), ~"hello"); } #[test] fn test_double_decode() { let stream: ~[u8] = ~[110,134,27,240,249,33,9,64]; let mut parser = BsonParser::new(stream); let d = parser._double(); match d { Double(d2) => { assert!(d2.approx_eq(&3.14159f64)); } _ => fail!("failed in a test case; how did I get here?") } } #[test] fn test_document_decode() { let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0]; let mut parser1 = BsonParser::new(stream1); let mut doc1 = BsonDocument::new(); doc1.put(~"foo", Bool(true)); assert_eq!(parser1.document().unwrap(), doc1); let stream2: ~[u8] = ~[45,0,0,0,4,102,111,111,0,22,0,0,0,2,48,0, 6,0,0,0,104,101,108,108,111,0,8,49,0,0, 0,2,98,97,122,0,4,0,0,0,113,117,120,0,0]; let mut inside = BsonDocument::new(); inside.put_all(~[(~"0", UString(~"hello")), (~"1", Bool(false))]); let mut doc2 = BsonDocument::new(); doc2.put_all(~[(~"foo", Array(~inside.clone())), (~"baz", UString(~"qux"))]); assert_eq!(decode(stream2).unwrap(), doc2); } #[test] fn test_binary_decode() { let stream: ~[u8] = ~[6,0,0,0,0,1,2,3,4,5,6]; let mut parser = BsonParser::new(stream); assert_eq!(parser._binary(), Binary(0, ~[1,2,3,4,5,6])); } #[test] fn
() { let mut doc = BsonDocument::new(); doc.put(~"foo", DBRef(~"bar", ~ObjectId(~[0u8,1,2,3,4,5,6,7,8,9,10,11]))); let stream: ~[u8] = ~[30,0,0,0,12,102,111,111,0,4,0,0,0,98,97,114,0,0,1,2,3,4,5,6,7,8,9,10,11,0]; assert_eq!(decode(stream).unwrap(), doc) } //TODO: get bson strings of torture-test objects #[bench] fn bench_basic_obj_decode(b: &mut BenchHarness) { do b.iter { let stream: ~[u8] = ~[45,0,0,0,4,102,111, 111,0,22,0,0,0,2,48,0,6,0,0,0,104,101,108, 108,111,0,8,49,0,0,0,2,98,97,122,0,4,0,0,0, 113,117,120,0,0]; decode(stream); } } }
test_dbref_encode
identifier_name
main.go
// perf-ingest listens to a PubSub Topic for new files that appear // in a storage bucket and then ingests those files into BigTable. package main import ( "context" "encoding/json" "errors" "flag" "fmt" "io" "log" "net/http" _ "net/http/pprof" "os"
"cloud.google.com/go/bigtable" "cloud.google.com/go/pubsub" "cloud.google.com/go/storage" "go.skia.org/infra/go/auth" "go.skia.org/infra/go/common" "go.skia.org/infra/go/git/gitinfo" "go.skia.org/infra/go/httputils" "go.skia.org/infra/go/metrics2" "go.skia.org/infra/go/paramtools" "go.skia.org/infra/go/query" "go.skia.org/infra/go/skerr" "go.skia.org/infra/go/sklog" "go.skia.org/infra/go/util" "go.skia.org/infra/go/vcsinfo" "go.skia.org/infra/perf/go/btts" "go.skia.org/infra/perf/go/config" "go.skia.org/infra/perf/go/ingestcommon" "go.skia.org/infra/perf/go/ingestevents" "google.golang.org/api/option" ) // flags var ( configName = flag.String("config_name", "nano", "Name of the perf ingester config to use.") local = flag.Bool("local", false, "Running locally if true. As opposed to in production.") port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')") promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')") ) const ( // MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally. MAX_PARALLEL_RECEIVES = 1 ) var ( // mutex protects hashCache. mutex = sync.Mutex{} // hashCache is a cache of results from calling vcs.IndexOf(). hashCache = map[string]int{} // pubSubClient is a client used for both receiving PubSub messages from GCS // and for sending ingestion notifications if the config specifies such a // Topic. pubSubClient *pubsub.Client // The configuration data for the selected Perf instance. cfg *config.PerfBigTableConfig ) var ( // NonRecoverableError is returned if the error is non-recoverable and we // should Ack the PubSub message. This might happen if, for example, a // non-JSON file gets dropped in the bucket. NonRecoverableError = errors.New("Non-recoverable ingestion error.") ) // getParamsAndValues returns two parallel slices, each slice contains the // params and then the float for a single value of a trace. It also returns the // consolidated ParamSet built from all the Params. func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.Params, []float32, paramtools.ParamSet) { params := []paramtools.Params{} values := []float32{} ps := paramtools.ParamSet{} for testName, allConfigs := range b.Results { for configName, result := range allConfigs { key := paramtools.Params(b.Key).Copy() key["test"] = testName key["config"] = configName key.Add(paramtools.Params(b.Options)) // If there is an options map inside the result add it to the params. if resultOptions, ok := result["options"]; ok { if opts, ok := resultOptions.(map[string]interface{}); ok { for k, vi := range opts { // Ignore the very long and not useful GL_ values, we can retrieve // them later via ptracestore.Details. if strings.HasPrefix(k, "GL_") { continue } if s, ok := vi.(string); ok { key[k] = s } } } } for k, vi := range result { if k == "options" || k == "samples" { continue } key["sub_result"] = k floatVal, ok := vi.(float64) if !ok { sklog.Errorf("Found a non-float64 in %v", result) continue } key = query.ForceValid(key) params = append(params, key.Copy()) values = append(values, float32(floatVal)) ps.AddParams(key) } } } ps.Normalize() return params, values, ps } func indexFromCache(hash string) (int, bool) { mutex.Lock() defer mutex.Unlock() index, ok := hashCache[hash] return index, ok } func indexToCache(hash string, index int) { mutex.Lock() defer mutex.Unlock() hashCache[hash] = index } // processSingleFile parses the contents of a single JSON file and writes the values into BigTable. // // If 'branches' is not empty then restrict to ingesting just the branches in the slice. func processSingleFile(ctx context.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error { benchData, err := ingestcommon.ParseBenchDataFromReader(r) if err != nil { sklog.Errorf("Failed to read or parse data: %s", err) return NonRecoverableError } branch, ok := benchData.Key["branch"] if ok { if len(branches) > 0 { if !util.In(branch, branches) { return nil } } } else { sklog.Infof("No branch name.") } params, values, paramset := getParamsAndValues(benchData) // Don't do any more work if there's no data to ingest. if len(params) == 0 { metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1) sklog.Infof("No data in: %q", filename) return nil } sklog.Infof("Processing %q", filename) index, ok := indexFromCache(benchData.Hash) if !ok { var err error index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { if err := vcs.Update(context.Background(), true, false); err != nil { return fmt.Errorf("Could not ingest, failed to pull: %s", err) } index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err) return NonRecoverableError } } indexToCache(benchData.Hash, index) } err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp) if err != nil { return err } return sendPubSubEvent(params, paramset, filename) } // sendPubSubEvent sends the unencoded params and paramset found in a single // ingested file to the PubSub topic specified in the selected Perf instances // configuration data. func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error { if cfg.FileIngestionTopicName == "" { return nil } traceIDs := make([]string, 0, len(params)) for _, p := range params { key, err := query.MakeKeyFast(p) if err != nil { continue } traceIDs = append(traceIDs, key) } ie := &ingestevents.IngestEvent{ TraceIDs: traceIDs, ParamSet: paramset, Filename: filename, } body, err := ingestevents.CreatePubSubBody(ie) if err != nil { return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName) } msg := &pubsub.Message{ Data: body, } ctx := context.Background() _, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx) return err } // Event is used to deserialize the PubSub data. // // The PubSub event data is a JSON serialized storage.ObjectAttrs object. // See https://cloud.google.com/storage/docs/pubsub-notifications#payload type Event struct { Bucket string `json:"bucket"` Name string `json:"name"` } func main() { common.InitWithMust( "perf-ingest", common.PrometheusOpt(promPort), common.MetricsLoggingOpt(), ) // nackCounter is the number files we weren't able to ingest. nackCounter := metrics2.GetCounter("nack", nil) // ackCounter is the number files we were able to ingest. ackCounter := metrics2.GetCounter("ack", nil) ctx := context.Background() var ok bool cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName] if !ok { sklog.Fatalf("Invalid --config value: %q", *configName) } hostname, err := os.Hostname() if err != nil { sklog.Fatalf("Failed to get hostname: %s", err) } ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub) if err != nil { sklog.Fatalf("Failed to create TokenSource: %s", err) } client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client() gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client)) if err != nil { sklog.Fatalf("Failed to create GCS client: %s", err) } pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts)) if err != nil { sklog.Fatal(err) } // When running in production we have every instance use the same topic name so that // they load-balance pulling items from the topic. subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod") if *local { // When running locally create a new topic for every host. subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname) } sub := pubSubClient.Subscription(subName) ok, err = sub.Exists(ctx) if err != nil { sklog.Fatalf("Failed checking subscription existence: %s", err) } if !ok { sub, err = pubSubClient.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{ Topic: pubSubClient.Topic(cfg.Topic), }) if err != nil { sklog.Fatalf("Failed creating subscription: %s", err) } } // How many Go routines should be processing messages? sub.ReceiveSettings.MaxOutstandingMessages = MAX_PARALLEL_RECEIVES sub.ReceiveSettings.NumGoroutines = MAX_PARALLEL_RECEIVES vcs, err := gitinfo.CloneOrUpdate(ctx, cfg.GitUrl, "/tmp/skia_ingest_checkout", true) if err != nil { sklog.Fatal(err) } store, err := btts.NewBigTableTraceStoreFromConfig(ctx, cfg, ts, true) if err != nil { sklog.Fatal(err) } // Process all incoming PubSub requests. go func() { for { // Wait for PubSub events. err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { // Set success to true if we should Ack the PubSub message, otherwise // the message will be Nack'd, and PubSub will try to send the message // again. success := false defer func() { if success { ackCounter.Inc(1) msg.Ack() } else { nackCounter.Inc(1) msg.Nack() } }() // Decode the event, which is a GCS event that a file was written. var event Event if err := json.Unmarshal(msg.Data, &event); err != nil { sklog.Error(err) return } // Transaction logs for android_ingest are written to the same bucket, // which we should ignore. if strings.Contains(event.Name, "/tx_log/") { // Ack the file so we don't process it again. success = true return } // Load the file. obj := gcsClient.Bucket(event.Bucket).Object(event.Name) attrs, err := obj.Attrs(ctx) if err != nil { sklog.Error(err) return } reader, err := obj.NewReader(ctx) if err != nil { sklog.Error(err) return } defer util.Close(reader) sklog.Infof("Filename: %q", attrs.Name) // Pull data out of file and write it into BigTable. fullName := fmt.Sprintf("gs://%s/%s", event.Bucket, event.Name) err = processSingleFile(ctx, store, vcs, fullName, reader, attrs.Created, cfg.Branches) if err := reader.Close(); err != nil { sklog.Errorf("Failed to close: %s", err) } if err == NonRecoverableError { success = true } else if err != nil { sklog.Errorf("Failed to write results: %s", err) return } success = true }) if err != nil { sklog.Errorf("Failed receiving pubsub message: %s", err) } } }() // Set up the http handler to indicate ready-ness and start serving. http.HandleFunc("/ready", httputils.ReadyHandleFunc) log.Fatal(http.ListenAndServe(*port, nil)) }
"strings" "sync" "time"
random_line_split
main.go
// perf-ingest listens to a PubSub Topic for new files that appear // in a storage bucket and then ingests those files into BigTable. package main import ( "context" "encoding/json" "errors" "flag" "fmt" "io" "log" "net/http" _ "net/http/pprof" "os" "strings" "sync" "time" "cloud.google.com/go/bigtable" "cloud.google.com/go/pubsub" "cloud.google.com/go/storage" "go.skia.org/infra/go/auth" "go.skia.org/infra/go/common" "go.skia.org/infra/go/git/gitinfo" "go.skia.org/infra/go/httputils" "go.skia.org/infra/go/metrics2" "go.skia.org/infra/go/paramtools" "go.skia.org/infra/go/query" "go.skia.org/infra/go/skerr" "go.skia.org/infra/go/sklog" "go.skia.org/infra/go/util" "go.skia.org/infra/go/vcsinfo" "go.skia.org/infra/perf/go/btts" "go.skia.org/infra/perf/go/config" "go.skia.org/infra/perf/go/ingestcommon" "go.skia.org/infra/perf/go/ingestevents" "google.golang.org/api/option" ) // flags var ( configName = flag.String("config_name", "nano", "Name of the perf ingester config to use.") local = flag.Bool("local", false, "Running locally if true. As opposed to in production.") port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')") promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')") ) const ( // MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally. MAX_PARALLEL_RECEIVES = 1 ) var ( // mutex protects hashCache. mutex = sync.Mutex{} // hashCache is a cache of results from calling vcs.IndexOf(). hashCache = map[string]int{} // pubSubClient is a client used for both receiving PubSub messages from GCS // and for sending ingestion notifications if the config specifies such a // Topic. pubSubClient *pubsub.Client // The configuration data for the selected Perf instance. cfg *config.PerfBigTableConfig ) var ( // NonRecoverableError is returned if the error is non-recoverable and we // should Ack the PubSub message. This might happen if, for example, a // non-JSON file gets dropped in the bucket. NonRecoverableError = errors.New("Non-recoverable ingestion error.") ) // getParamsAndValues returns two parallel slices, each slice contains the // params and then the float for a single value of a trace. It also returns the // consolidated ParamSet built from all the Params. func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.Params, []float32, paramtools.ParamSet) { params := []paramtools.Params{} values := []float32{} ps := paramtools.ParamSet{} for testName, allConfigs := range b.Results { for configName, result := range allConfigs { key := paramtools.Params(b.Key).Copy() key["test"] = testName key["config"] = configName key.Add(paramtools.Params(b.Options)) // If there is an options map inside the result add it to the params. if resultOptions, ok := result["options"]; ok { if opts, ok := resultOptions.(map[string]interface{}); ok { for k, vi := range opts { // Ignore the very long and not useful GL_ values, we can retrieve // them later via ptracestore.Details. if strings.HasPrefix(k, "GL_") { continue } if s, ok := vi.(string); ok { key[k] = s } } } } for k, vi := range result { if k == "options" || k == "samples" { continue } key["sub_result"] = k floatVal, ok := vi.(float64) if !ok { sklog.Errorf("Found a non-float64 in %v", result) continue } key = query.ForceValid(key) params = append(params, key.Copy()) values = append(values, float32(floatVal)) ps.AddParams(key) } } } ps.Normalize() return params, values, ps } func indexFromCache(hash string) (int, bool) { mutex.Lock() defer mutex.Unlock() index, ok := hashCache[hash] return index, ok } func indexToCache(hash string, index int) { mutex.Lock() defer mutex.Unlock() hashCache[hash] = index } // processSingleFile parses the contents of a single JSON file and writes the values into BigTable. // // If 'branches' is not empty then restrict to ingesting just the branches in the slice. func processSingleFile(ctx context.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error { benchData, err := ingestcommon.ParseBenchDataFromReader(r) if err != nil { sklog.Errorf("Failed to read or parse data: %s", err) return NonRecoverableError } branch, ok := benchData.Key["branch"] if ok { if len(branches) > 0 { if !util.In(branch, branches) { return nil } } } else { sklog.Infof("No branch name.") } params, values, paramset := getParamsAndValues(benchData) // Don't do any more work if there's no data to ingest. if len(params) == 0 { metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1) sklog.Infof("No data in: %q", filename) return nil } sklog.Infof("Processing %q", filename) index, ok := indexFromCache(benchData.Hash) if !ok { var err error index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { if err := vcs.Update(context.Background(), true, false); err != nil { return fmt.Errorf("Could not ingest, failed to pull: %s", err) } index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err) return NonRecoverableError } } indexToCache(benchData.Hash, index) } err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp) if err != nil { return err } return sendPubSubEvent(params, paramset, filename) } // sendPubSubEvent sends the unencoded params and paramset found in a single // ingested file to the PubSub topic specified in the selected Perf instances // configuration data. func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error { if cfg.FileIngestionTopicName == "" { return nil } traceIDs := make([]string, 0, len(params)) for _, p := range params { key, err := query.MakeKeyFast(p) if err != nil { continue } traceIDs = append(traceIDs, key) } ie := &ingestevents.IngestEvent{ TraceIDs: traceIDs, ParamSet: paramset, Filename: filename, } body, err := ingestevents.CreatePubSubBody(ie) if err != nil { return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName) } msg := &pubsub.Message{ Data: body, } ctx := context.Background() _, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx) return err } // Event is used to deserialize the PubSub data. // // The PubSub event data is a JSON serialized storage.ObjectAttrs object. // See https://cloud.google.com/storage/docs/pubsub-notifications#payload type Event struct { Bucket string `json:"bucket"` Name string `json:"name"` } func main() { common.InitWithMust( "perf-ingest", common.PrometheusOpt(promPort), common.MetricsLoggingOpt(), ) // nackCounter is the number files we weren't able to ingest. nackCounter := metrics2.GetCounter("nack", nil) // ackCounter is the number files we were able to ingest. ackCounter := metrics2.GetCounter("ack", nil) ctx := context.Background() var ok bool cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName] if !ok { sklog.Fatalf("Invalid --config value: %q", *configName) } hostname, err := os.Hostname() if err != nil { sklog.Fatalf("Failed to get hostname: %s", err) } ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub) if err != nil { sklog.Fatalf("Failed to create TokenSource: %s", err) } client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client() gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client)) if err != nil { sklog.Fatalf("Failed to create GCS client: %s", err) } pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts)) if err != nil { sklog.Fatal(err) } // When running in production we have every instance use the same topic name so that // they load-balance pulling items from the topic. subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod") if *local { // When running locally create a new topic for every host. subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname) } sub := pubSubClient.Subscription(subName) ok, err = sub.Exists(ctx) if err != nil { sklog.Fatalf("Failed checking subscription existence: %s", err) } if !ok { sub, err = pubSubClient.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{ Topic: pubSubClient.Topic(cfg.Topic), }) if err != nil { sklog.Fatalf("Failed creating subscription: %s", err) } } // How many Go routines should be processing messages? sub.ReceiveSettings.MaxOutstandingMessages = MAX_PARALLEL_RECEIVES sub.ReceiveSettings.NumGoroutines = MAX_PARALLEL_RECEIVES vcs, err := gitinfo.CloneOrUpdate(ctx, cfg.GitUrl, "/tmp/skia_ingest_checkout", true) if err != nil { sklog.Fatal(err) } store, err := btts.NewBigTableTraceStoreFromConfig(ctx, cfg, ts, true) if err != nil { sklog.Fatal(err) } // Process all incoming PubSub requests. go func() { for
}() // Set up the http handler to indicate ready-ness and start serving. http.HandleFunc("/ready", httputils.ReadyHandleFunc) log.Fatal(http.ListenAndServe(*port, nil)) }
{ // Wait for PubSub events. err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { // Set success to true if we should Ack the PubSub message, otherwise // the message will be Nack'd, and PubSub will try to send the message // again. success := false defer func() { if success { ackCounter.Inc(1) msg.Ack() } else { nackCounter.Inc(1) msg.Nack() } }() // Decode the event, which is a GCS event that a file was written. var event Event if err := json.Unmarshal(msg.Data, &event); err != nil { sklog.Error(err) return } // Transaction logs for android_ingest are written to the same bucket, // which we should ignore. if strings.Contains(event.Name, "/tx_log/") { // Ack the file so we don't process it again. success = true return } // Load the file. obj := gcsClient.Bucket(event.Bucket).Object(event.Name) attrs, err := obj.Attrs(ctx) if err != nil { sklog.Error(err) return } reader, err := obj.NewReader(ctx) if err != nil { sklog.Error(err) return } defer util.Close(reader) sklog.Infof("Filename: %q", attrs.Name) // Pull data out of file and write it into BigTable. fullName := fmt.Sprintf("gs://%s/%s", event.Bucket, event.Name) err = processSingleFile(ctx, store, vcs, fullName, reader, attrs.Created, cfg.Branches) if err := reader.Close(); err != nil { sklog.Errorf("Failed to close: %s", err) } if err == NonRecoverableError { success = true } else if err != nil { sklog.Errorf("Failed to write results: %s", err) return } success = true }) if err != nil { sklog.Errorf("Failed receiving pubsub message: %s", err) } }
conditional_block
main.go
// perf-ingest listens to a PubSub Topic for new files that appear // in a storage bucket and then ingests those files into BigTable. package main import ( "context" "encoding/json" "errors" "flag" "fmt" "io" "log" "net/http" _ "net/http/pprof" "os" "strings" "sync" "time" "cloud.google.com/go/bigtable" "cloud.google.com/go/pubsub" "cloud.google.com/go/storage" "go.skia.org/infra/go/auth" "go.skia.org/infra/go/common" "go.skia.org/infra/go/git/gitinfo" "go.skia.org/infra/go/httputils" "go.skia.org/infra/go/metrics2" "go.skia.org/infra/go/paramtools" "go.skia.org/infra/go/query" "go.skia.org/infra/go/skerr" "go.skia.org/infra/go/sklog" "go.skia.org/infra/go/util" "go.skia.org/infra/go/vcsinfo" "go.skia.org/infra/perf/go/btts" "go.skia.org/infra/perf/go/config" "go.skia.org/infra/perf/go/ingestcommon" "go.skia.org/infra/perf/go/ingestevents" "google.golang.org/api/option" ) // flags var ( configName = flag.String("config_name", "nano", "Name of the perf ingester config to use.") local = flag.Bool("local", false, "Running locally if true. As opposed to in production.") port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')") promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')") ) const ( // MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally. MAX_PARALLEL_RECEIVES = 1 ) var ( // mutex protects hashCache. mutex = sync.Mutex{} // hashCache is a cache of results from calling vcs.IndexOf(). hashCache = map[string]int{} // pubSubClient is a client used for both receiving PubSub messages from GCS // and for sending ingestion notifications if the config specifies such a // Topic. pubSubClient *pubsub.Client // The configuration data for the selected Perf instance. cfg *config.PerfBigTableConfig ) var ( // NonRecoverableError is returned if the error is non-recoverable and we // should Ack the PubSub message. This might happen if, for example, a // non-JSON file gets dropped in the bucket. NonRecoverableError = errors.New("Non-recoverable ingestion error.") ) // getParamsAndValues returns two parallel slices, each slice contains the // params and then the float for a single value of a trace. It also returns the // consolidated ParamSet built from all the Params. func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.Params, []float32, paramtools.ParamSet) { params := []paramtools.Params{} values := []float32{} ps := paramtools.ParamSet{} for testName, allConfigs := range b.Results { for configName, result := range allConfigs { key := paramtools.Params(b.Key).Copy() key["test"] = testName key["config"] = configName key.Add(paramtools.Params(b.Options)) // If there is an options map inside the result add it to the params. if resultOptions, ok := result["options"]; ok { if opts, ok := resultOptions.(map[string]interface{}); ok { for k, vi := range opts { // Ignore the very long and not useful GL_ values, we can retrieve // them later via ptracestore.Details. if strings.HasPrefix(k, "GL_") { continue } if s, ok := vi.(string); ok { key[k] = s } } } } for k, vi := range result { if k == "options" || k == "samples" { continue } key["sub_result"] = k floatVal, ok := vi.(float64) if !ok { sklog.Errorf("Found a non-float64 in %v", result) continue } key = query.ForceValid(key) params = append(params, key.Copy()) values = append(values, float32(floatVal)) ps.AddParams(key) } } } ps.Normalize() return params, values, ps } func indexFromCache(hash string) (int, bool) { mutex.Lock() defer mutex.Unlock() index, ok := hashCache[hash] return index, ok } func indexToCache(hash string, index int)
// processSingleFile parses the contents of a single JSON file and writes the values into BigTable. // // If 'branches' is not empty then restrict to ingesting just the branches in the slice. func processSingleFile(ctx context.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error { benchData, err := ingestcommon.ParseBenchDataFromReader(r) if err != nil { sklog.Errorf("Failed to read or parse data: %s", err) return NonRecoverableError } branch, ok := benchData.Key["branch"] if ok { if len(branches) > 0 { if !util.In(branch, branches) { return nil } } } else { sklog.Infof("No branch name.") } params, values, paramset := getParamsAndValues(benchData) // Don't do any more work if there's no data to ingest. if len(params) == 0 { metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1) sklog.Infof("No data in: %q", filename) return nil } sklog.Infof("Processing %q", filename) index, ok := indexFromCache(benchData.Hash) if !ok { var err error index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { if err := vcs.Update(context.Background(), true, false); err != nil { return fmt.Errorf("Could not ingest, failed to pull: %s", err) } index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err) return NonRecoverableError } } indexToCache(benchData.Hash, index) } err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp) if err != nil { return err } return sendPubSubEvent(params, paramset, filename) } // sendPubSubEvent sends the unencoded params and paramset found in a single // ingested file to the PubSub topic specified in the selected Perf instances // configuration data. func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error { if cfg.FileIngestionTopicName == "" { return nil } traceIDs := make([]string, 0, len(params)) for _, p := range params { key, err := query.MakeKeyFast(p) if err != nil { continue } traceIDs = append(traceIDs, key) } ie := &ingestevents.IngestEvent{ TraceIDs: traceIDs, ParamSet: paramset, Filename: filename, } body, err := ingestevents.CreatePubSubBody(ie) if err != nil { return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName) } msg := &pubsub.Message{ Data: body, } ctx := context.Background() _, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx) return err } // Event is used to deserialize the PubSub data. // // The PubSub event data is a JSON serialized storage.ObjectAttrs object. // See https://cloud.google.com/storage/docs/pubsub-notifications#payload type Event struct { Bucket string `json:"bucket"` Name string `json:"name"` } func main() { common.InitWithMust( "perf-ingest", common.PrometheusOpt(promPort), common.MetricsLoggingOpt(), ) // nackCounter is the number files we weren't able to ingest. nackCounter := metrics2.GetCounter("nack", nil) // ackCounter is the number files we were able to ingest. ackCounter := metrics2.GetCounter("ack", nil) ctx := context.Background() var ok bool cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName] if !ok { sklog.Fatalf("Invalid --config value: %q", *configName) } hostname, err := os.Hostname() if err != nil { sklog.Fatalf("Failed to get hostname: %s", err) } ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub) if err != nil { sklog.Fatalf("Failed to create TokenSource: %s", err) } client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client() gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client)) if err != nil { sklog.Fatalf("Failed to create GCS client: %s", err) } pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts)) if err != nil { sklog.Fatal(err) } // When running in production we have every instance use the same topic name so that // they load-balance pulling items from the topic. subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod") if *local { // When running locally create a new topic for every host. subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname) } sub := pubSubClient.Subscription(subName) ok, err = sub.Exists(ctx) if err != nil { sklog.Fatalf("Failed checking subscription existence: %s", err) } if !ok { sub, err = pubSubClient.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{ Topic: pubSubClient.Topic(cfg.Topic), }) if err != nil { sklog.Fatalf("Failed creating subscription: %s", err) } } // How many Go routines should be processing messages? sub.ReceiveSettings.MaxOutstandingMessages = MAX_PARALLEL_RECEIVES sub.ReceiveSettings.NumGoroutines = MAX_PARALLEL_RECEIVES vcs, err := gitinfo.CloneOrUpdate(ctx, cfg.GitUrl, "/tmp/skia_ingest_checkout", true) if err != nil { sklog.Fatal(err) } store, err := btts.NewBigTableTraceStoreFromConfig(ctx, cfg, ts, true) if err != nil { sklog.Fatal(err) } // Process all incoming PubSub requests. go func() { for { // Wait for PubSub events. err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { // Set success to true if we should Ack the PubSub message, otherwise // the message will be Nack'd, and PubSub will try to send the message // again. success := false defer func() { if success { ackCounter.Inc(1) msg.Ack() } else { nackCounter.Inc(1) msg.Nack() } }() // Decode the event, which is a GCS event that a file was written. var event Event if err := json.Unmarshal(msg.Data, &event); err != nil { sklog.Error(err) return } // Transaction logs for android_ingest are written to the same bucket, // which we should ignore. if strings.Contains(event.Name, "/tx_log/") { // Ack the file so we don't process it again. success = true return } // Load the file. obj := gcsClient.Bucket(event.Bucket).Object(event.Name) attrs, err := obj.Attrs(ctx) if err != nil { sklog.Error(err) return } reader, err := obj.NewReader(ctx) if err != nil { sklog.Error(err) return } defer util.Close(reader) sklog.Infof("Filename: %q", attrs.Name) // Pull data out of file and write it into BigTable. fullName := fmt.Sprintf("gs://%s/%s", event.Bucket, event.Name) err = processSingleFile(ctx, store, vcs, fullName, reader, attrs.Created, cfg.Branches) if err := reader.Close(); err != nil { sklog.Errorf("Failed to close: %s", err) } if err == NonRecoverableError { success = true } else if err != nil { sklog.Errorf("Failed to write results: %s", err) return } success = true }) if err != nil { sklog.Errorf("Failed receiving pubsub message: %s", err) } } }() // Set up the http handler to indicate ready-ness and start serving. http.HandleFunc("/ready", httputils.ReadyHandleFunc) log.Fatal(http.ListenAndServe(*port, nil)) }
{ mutex.Lock() defer mutex.Unlock() hashCache[hash] = index }
identifier_body
main.go
// perf-ingest listens to a PubSub Topic for new files that appear // in a storage bucket and then ingests those files into BigTable. package main import ( "context" "encoding/json" "errors" "flag" "fmt" "io" "log" "net/http" _ "net/http/pprof" "os" "strings" "sync" "time" "cloud.google.com/go/bigtable" "cloud.google.com/go/pubsub" "cloud.google.com/go/storage" "go.skia.org/infra/go/auth" "go.skia.org/infra/go/common" "go.skia.org/infra/go/git/gitinfo" "go.skia.org/infra/go/httputils" "go.skia.org/infra/go/metrics2" "go.skia.org/infra/go/paramtools" "go.skia.org/infra/go/query" "go.skia.org/infra/go/skerr" "go.skia.org/infra/go/sklog" "go.skia.org/infra/go/util" "go.skia.org/infra/go/vcsinfo" "go.skia.org/infra/perf/go/btts" "go.skia.org/infra/perf/go/config" "go.skia.org/infra/perf/go/ingestcommon" "go.skia.org/infra/perf/go/ingestevents" "google.golang.org/api/option" ) // flags var ( configName = flag.String("config_name", "nano", "Name of the perf ingester config to use.") local = flag.Bool("local", false, "Running locally if true. As opposed to in production.") port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')") promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')") ) const ( // MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally. MAX_PARALLEL_RECEIVES = 1 ) var ( // mutex protects hashCache. mutex = sync.Mutex{} // hashCache is a cache of results from calling vcs.IndexOf(). hashCache = map[string]int{} // pubSubClient is a client used for both receiving PubSub messages from GCS // and for sending ingestion notifications if the config specifies such a // Topic. pubSubClient *pubsub.Client // The configuration data for the selected Perf instance. cfg *config.PerfBigTableConfig ) var ( // NonRecoverableError is returned if the error is non-recoverable and we // should Ack the PubSub message. This might happen if, for example, a // non-JSON file gets dropped in the bucket. NonRecoverableError = errors.New("Non-recoverable ingestion error.") ) // getParamsAndValues returns two parallel slices, each slice contains the // params and then the float for a single value of a trace. It also returns the // consolidated ParamSet built from all the Params. func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.Params, []float32, paramtools.ParamSet) { params := []paramtools.Params{} values := []float32{} ps := paramtools.ParamSet{} for testName, allConfigs := range b.Results { for configName, result := range allConfigs { key := paramtools.Params(b.Key).Copy() key["test"] = testName key["config"] = configName key.Add(paramtools.Params(b.Options)) // If there is an options map inside the result add it to the params. if resultOptions, ok := result["options"]; ok { if opts, ok := resultOptions.(map[string]interface{}); ok { for k, vi := range opts { // Ignore the very long and not useful GL_ values, we can retrieve // them later via ptracestore.Details. if strings.HasPrefix(k, "GL_") { continue } if s, ok := vi.(string); ok { key[k] = s } } } } for k, vi := range result { if k == "options" || k == "samples" { continue } key["sub_result"] = k floatVal, ok := vi.(float64) if !ok { sklog.Errorf("Found a non-float64 in %v", result) continue } key = query.ForceValid(key) params = append(params, key.Copy()) values = append(values, float32(floatVal)) ps.AddParams(key) } } } ps.Normalize() return params, values, ps } func indexFromCache(hash string) (int, bool) { mutex.Lock() defer mutex.Unlock() index, ok := hashCache[hash] return index, ok } func
(hash string, index int) { mutex.Lock() defer mutex.Unlock() hashCache[hash] = index } // processSingleFile parses the contents of a single JSON file and writes the values into BigTable. // // If 'branches' is not empty then restrict to ingesting just the branches in the slice. func processSingleFile(ctx context.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error { benchData, err := ingestcommon.ParseBenchDataFromReader(r) if err != nil { sklog.Errorf("Failed to read or parse data: %s", err) return NonRecoverableError } branch, ok := benchData.Key["branch"] if ok { if len(branches) > 0 { if !util.In(branch, branches) { return nil } } } else { sklog.Infof("No branch name.") } params, values, paramset := getParamsAndValues(benchData) // Don't do any more work if there's no data to ingest. if len(params) == 0 { metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1) sklog.Infof("No data in: %q", filename) return nil } sklog.Infof("Processing %q", filename) index, ok := indexFromCache(benchData.Hash) if !ok { var err error index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { if err := vcs.Update(context.Background(), true, false); err != nil { return fmt.Errorf("Could not ingest, failed to pull: %s", err) } index, err = vcs.IndexOf(ctx, benchData.Hash) if err != nil { sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err) return NonRecoverableError } } indexToCache(benchData.Hash, index) } err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp) if err != nil { return err } return sendPubSubEvent(params, paramset, filename) } // sendPubSubEvent sends the unencoded params and paramset found in a single // ingested file to the PubSub topic specified in the selected Perf instances // configuration data. func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error { if cfg.FileIngestionTopicName == "" { return nil } traceIDs := make([]string, 0, len(params)) for _, p := range params { key, err := query.MakeKeyFast(p) if err != nil { continue } traceIDs = append(traceIDs, key) } ie := &ingestevents.IngestEvent{ TraceIDs: traceIDs, ParamSet: paramset, Filename: filename, } body, err := ingestevents.CreatePubSubBody(ie) if err != nil { return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName) } msg := &pubsub.Message{ Data: body, } ctx := context.Background() _, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx) return err } // Event is used to deserialize the PubSub data. // // The PubSub event data is a JSON serialized storage.ObjectAttrs object. // See https://cloud.google.com/storage/docs/pubsub-notifications#payload type Event struct { Bucket string `json:"bucket"` Name string `json:"name"` } func main() { common.InitWithMust( "perf-ingest", common.PrometheusOpt(promPort), common.MetricsLoggingOpt(), ) // nackCounter is the number files we weren't able to ingest. nackCounter := metrics2.GetCounter("nack", nil) // ackCounter is the number files we were able to ingest. ackCounter := metrics2.GetCounter("ack", nil) ctx := context.Background() var ok bool cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName] if !ok { sklog.Fatalf("Invalid --config value: %q", *configName) } hostname, err := os.Hostname() if err != nil { sklog.Fatalf("Failed to get hostname: %s", err) } ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub) if err != nil { sklog.Fatalf("Failed to create TokenSource: %s", err) } client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client() gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client)) if err != nil { sklog.Fatalf("Failed to create GCS client: %s", err) } pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts)) if err != nil { sklog.Fatal(err) } // When running in production we have every instance use the same topic name so that // they load-balance pulling items from the topic. subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod") if *local { // When running locally create a new topic for every host. subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname) } sub := pubSubClient.Subscription(subName) ok, err = sub.Exists(ctx) if err != nil { sklog.Fatalf("Failed checking subscription existence: %s", err) } if !ok { sub, err = pubSubClient.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{ Topic: pubSubClient.Topic(cfg.Topic), }) if err != nil { sklog.Fatalf("Failed creating subscription: %s", err) } } // How many Go routines should be processing messages? sub.ReceiveSettings.MaxOutstandingMessages = MAX_PARALLEL_RECEIVES sub.ReceiveSettings.NumGoroutines = MAX_PARALLEL_RECEIVES vcs, err := gitinfo.CloneOrUpdate(ctx, cfg.GitUrl, "/tmp/skia_ingest_checkout", true) if err != nil { sklog.Fatal(err) } store, err := btts.NewBigTableTraceStoreFromConfig(ctx, cfg, ts, true) if err != nil { sklog.Fatal(err) } // Process all incoming PubSub requests. go func() { for { // Wait for PubSub events. err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { // Set success to true if we should Ack the PubSub message, otherwise // the message will be Nack'd, and PubSub will try to send the message // again. success := false defer func() { if success { ackCounter.Inc(1) msg.Ack() } else { nackCounter.Inc(1) msg.Nack() } }() // Decode the event, which is a GCS event that a file was written. var event Event if err := json.Unmarshal(msg.Data, &event); err != nil { sklog.Error(err) return } // Transaction logs for android_ingest are written to the same bucket, // which we should ignore. if strings.Contains(event.Name, "/tx_log/") { // Ack the file so we don't process it again. success = true return } // Load the file. obj := gcsClient.Bucket(event.Bucket).Object(event.Name) attrs, err := obj.Attrs(ctx) if err != nil { sklog.Error(err) return } reader, err := obj.NewReader(ctx) if err != nil { sklog.Error(err) return } defer util.Close(reader) sklog.Infof("Filename: %q", attrs.Name) // Pull data out of file and write it into BigTable. fullName := fmt.Sprintf("gs://%s/%s", event.Bucket, event.Name) err = processSingleFile(ctx, store, vcs, fullName, reader, attrs.Created, cfg.Branches) if err := reader.Close(); err != nil { sklog.Errorf("Failed to close: %s", err) } if err == NonRecoverableError { success = true } else if err != nil { sklog.Errorf("Failed to write results: %s", err) return } success = true }) if err != nil { sklog.Errorf("Failed receiving pubsub message: %s", err) } } }() // Set up the http handler to indicate ready-ness and start serving. http.HandleFunc("/ready", httputils.ReadyHandleFunc) log.Fatal(http.ListenAndServe(*port, nil)) }
indexToCache
identifier_name
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, LabelClause, NotClause, OrClause, Query, ResultClause}; use wptfyi::{interop, metadata, result, run, search, Wptfyi}; fn fx_failures_query(labels: &[&str]) -> Query { let pass_statuses = &[Status::Ok, Status::Pass]; let mut root_clause = AndClause { and: Vec::with_capacity(3), }; for status in pass_statuses.iter() { root_clause.push(Clause::Not(NotClause { not: Box::new(Clause::Result(ResultClause { browser_name: "firefox".to_owned(), status: status.clone(), })), })); } if !labels.is_empty() { let mut labels_clause = OrClause { or: Vec::with_capacity(labels.len()), }; for label in labels { labels_clause.push(Clause::Label(LabelClause { label: (*label).into(), })); } root_clause.push(Clause::Or(labels_clause)); } Query { query: Clause::And(root_clause), } } fn get_run_data(wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> { let mut runs = wptfyi.runs(); for product in ["chrome", "firefox", "safari"].iter() { runs.add_product(product, "experimental") } runs.add_label("master"); runs.set_max_count(100); Ok(run::parse(&get(client, &String::from(runs.url()), None)?)?) } fn get_metadata( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, Vec<MetadataEntry>>> { let mut metadata = wptfyi.metadata(); for product in ["firefox"].iter() { metadata.add_product(product) } Ok(metadata::parse(&get( client, &String::from(metadata.url()), None, )?)?) } pub fn get_fx_failures( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, run_ids: &[i64], labels: &[&str], ) -> Result<result::SearchData> { let mut search = wptfyi.search(); for product in ["chrome", "firefox", "safari"].iter() { search.add_product(product, "experimental") } search.set_query(run_ids, fx_failures_query(labels)); search.add_label("master"); Ok(search::parse(&post( client, &String::from(search.url()), None, search.body(), )?)?) } pub fn get_interop_data( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::YearData>> { let runs = wptfyi.interop_data(); Ok(interop::parse(&get( client, &String::from(runs.url()), None, )?)?) } pub fn get_interop_categories( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::Categories>> { Ok(interop::parse_categories(&get( client, &String::from(wptfyi.interop_categories().url()), None, )?)?) } pub fn get_interop_scores( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, browser_channel: interop::BrowserChannel, ) -> Result<Vec<interop::ScoreRow>> { Ok(interop::parse_scores(&get( client, &String::from(wptfyi.interop_scores(browser_channel).url()), None, )?)?) } fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> { let mut runs_by_commit = run::runs_by_commit(runs); let latest_rev = runs_by_commit .iter() .filter(|(_, value)| value.len() == 3) .max_by(|(_, value_1), (_, value_2)| { let date_1 = value_1.iter().map(|x| x.created_at).max(); let date_2 = value_2.iter().map(|x| x.created_at).max(); date_1.cmp(&date_2) }) .map(|(key, _)| key.clone()); latest_rev .and_then(|x| runs_by_commit.remove(&x)) .ok_or_else(|| anyhow!("Failed to find any complete runs")) } pub fn write_focus_area( fyi: &Wptfyi, client: &reqwest::blocking::Client, name: &str, focus_area: &FocusArea, run_ids: &[i64], categories_by_name: &BTreeMap<String, &Category>, metadata: &BTreeMap<String, Vec<MetadataEntry>>, ) -> Result<()> { if !focus_area.counts_toward_score { return Ok(()); } let labels = &categories_by_name .get(name) .ok_or_else(|| anyhow!("Didn't find category {}", name))? .labels; let path = format!("../docs/interop-2023/{}.csv", name); let data_path = Path::new(&path); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let results = get_fx_failures( &fyi, &client, &run_ids, &labels .iter() .filter_map(|x| { if x.starts_with("interop-") { Some(x.as_ref()) } else { None } }) .collect::<Vec<&str>>(), )?; let order = &["firefox", "chrome", "safari"]; let maybe_browser_list = results .runs .iter() .map(|x| order.iter().position(|target| *target == x.browser_name)) .collect::<Option<Vec<usize>>>(); if maybe_browser_list.is_none() { return Err(anyhow!("Didn't get results for all three browsers")); } let browser_list = maybe_browser_list.unwrap(); writer.write_record([ "Test", "Firefox Failures", "Chrome Failures", "Safari Failures", "Bugs", ])?; for result in results.results.iter() { let mut scores = vec![String::new(), String::new(), String::new()]; for (output_idx, browser_idx) in browser_list.iter().enumerate() { if let Some(status) = result.legacy_status.get(*browser_idx) { if output_idx == 0 { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total)); } else { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total - status.passes)); } } } let mut bugs = BTreeSet::new(); if let Some(test_meta) = metadata.get(&result.test) { for metadata_entry in test_meta.iter() { if metadata_entry.product != "firefox" || !metadata_entry .url .starts_with("https://bugzilla.mozilla.org") { continue; } // For now add all bugs irrespective of status or subtest if let Ok(bug_url) = Url::parse(&metadata_entry.url) { if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") { bugs.insert(bug_id.into_owned()); } } } } let mut bugs_col = String::with_capacity(8 * bugs.len()); for bug in bugs.iter() { if !bugs_col.is_empty() { bugs_col.push(' '); } bugs_col.push_str(bug); } let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col]; writer.write_record(record)?; } Ok(()) } pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> { let mut columns = Vec::with_capacity(focus_areas.len()); for (name, data) in focus_areas.iter() { if data.counts_toward_score { columns.push(name.as_ref()); } } columns } fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64>
pub fn write_browser_interop_scores( browsers: &[&str], scores: &[interop::ScoreRow], interop_2023_data: &interop::YearData, ) -> Result<()> { let browser_columns = interop_columns(&interop_2023_data.focus_areas); let data_path = Path::new("../docs/interop-2023/scores.csv"); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let mut headers = Vec::with_capacity(browsers.len() + 1); headers.push("date"); headers.extend_from_slice(browsers); writer.write_record(headers)?; let mut output: Vec<String> = Vec::with_capacity(browsers.len() + 1); for row in scores { output.resize(0, "".into()); output.push( row.get("date") .ok_or_else(|| anyhow!("Failed to read date"))? .into(), ); for browser in browsers { let score = browser_score(browser, &browser_columns, row)?; output.push(format!("{:.2}", score)) } writer.write_record(&output)?; } Ok(()) } pub fn run() -> Result<()> { let client = network::client(); let fyi = Wptfyi::new(None); let runs = get_run_data(&fyi, &client)?; let run_ids = latest_runs(&runs)? .iter() .map(|x| x.id) .collect::<Vec<i64>>(); let interop_data = get_interop_data(&fyi, &client)?; let interop_2023_data = interop_data .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 metadata"))?; let interop_categories = get_interop_categories(&fyi, &client)?; let interop_2023_categories = interop_categories .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 categories"))?; let categories_by_name = interop_2023_categories.by_name(); let metadata = get_metadata(&fyi, &client)?; for (name, focus_area) in interop_2023_data.focus_areas.iter() { write_focus_area( &fyi, &client, name, focus_area, &run_ids, &categories_by_name, &metadata, )?; } let scores = get_interop_scores(&fyi, &client, interop::BrowserChannel::Experimental)?; write_browser_interop_scores(&["firefox", "chrome", "safari"], &scores, interop_2023_data)?; Ok(()) }
{ let mut total_score: u64 = 0; for column in columns { let column = format!("{}-{}", browser, column); let score = row .get(&column) .ok_or_else(|| anyhow!("Failed to get column {}", column))?; let value: u64 = score .parse::<u64>() .map_err(|_| anyhow!("Failed to parse score"))?; total_score += value; } Ok(total_score as f64 / (10 * columns.len()) as f64) }
identifier_body
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, LabelClause, NotClause, OrClause, Query, ResultClause}; use wptfyi::{interop, metadata, result, run, search, Wptfyi}; fn fx_failures_query(labels: &[&str]) -> Query { let pass_statuses = &[Status::Ok, Status::Pass]; let mut root_clause = AndClause { and: Vec::with_capacity(3), }; for status in pass_statuses.iter() { root_clause.push(Clause::Not(NotClause { not: Box::new(Clause::Result(ResultClause { browser_name: "firefox".to_owned(), status: status.clone(), })), })); } if !labels.is_empty() { let mut labels_clause = OrClause { or: Vec::with_capacity(labels.len()), }; for label in labels { labels_clause.push(Clause::Label(LabelClause { label: (*label).into(), })); } root_clause.push(Clause::Or(labels_clause)); } Query { query: Clause::And(root_clause), } } fn get_run_data(wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> { let mut runs = wptfyi.runs(); for product in ["chrome", "firefox", "safari"].iter() { runs.add_product(product, "experimental") } runs.add_label("master"); runs.set_max_count(100); Ok(run::parse(&get(client, &String::from(runs.url()), None)?)?) } fn get_metadata( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, Vec<MetadataEntry>>> { let mut metadata = wptfyi.metadata(); for product in ["firefox"].iter() { metadata.add_product(product) } Ok(metadata::parse(&get( client, &String::from(metadata.url()), None, )?)?) } pub fn get_fx_failures( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, run_ids: &[i64], labels: &[&str], ) -> Result<result::SearchData> { let mut search = wptfyi.search(); for product in ["chrome", "firefox", "safari"].iter() { search.add_product(product, "experimental") } search.set_query(run_ids, fx_failures_query(labels)); search.add_label("master"); Ok(search::parse(&post( client, &String::from(search.url()), None, search.body(), )?)?) } pub fn get_interop_data( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::YearData>> { let runs = wptfyi.interop_data(); Ok(interop::parse(&get( client, &String::from(runs.url()), None, )?)?) } pub fn get_interop_categories( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::Categories>> { Ok(interop::parse_categories(&get( client, &String::from(wptfyi.interop_categories().url()), None, )?)?) } pub fn get_interop_scores( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, browser_channel: interop::BrowserChannel, ) -> Result<Vec<interop::ScoreRow>> { Ok(interop::parse_scores(&get( client, &String::from(wptfyi.interop_scores(browser_channel).url()), None, )?)?) } fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> { let mut runs_by_commit = run::runs_by_commit(runs); let latest_rev = runs_by_commit .iter() .filter(|(_, value)| value.len() == 3) .max_by(|(_, value_1), (_, value_2)| { let date_1 = value_1.iter().map(|x| x.created_at).max(); let date_2 = value_2.iter().map(|x| x.created_at).max(); date_1.cmp(&date_2) }) .map(|(key, _)| key.clone()); latest_rev .and_then(|x| runs_by_commit.remove(&x)) .ok_or_else(|| anyhow!("Failed to find any complete runs")) } pub fn write_focus_area( fyi: &Wptfyi, client: &reqwest::blocking::Client, name: &str, focus_area: &FocusArea, run_ids: &[i64], categories_by_name: &BTreeMap<String, &Category>, metadata: &BTreeMap<String, Vec<MetadataEntry>>, ) -> Result<()> { if !focus_area.counts_toward_score { return Ok(()); } let labels = &categories_by_name .get(name) .ok_or_else(|| anyhow!("Didn't find category {}", name))? .labels; let path = format!("../docs/interop-2023/{}.csv", name); let data_path = Path::new(&path); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let results = get_fx_failures( &fyi, &client, &run_ids, &labels .iter() .filter_map(|x| { if x.starts_with("interop-") { Some(x.as_ref()) } else { None } }) .collect::<Vec<&str>>(), )?; let order = &["firefox", "chrome", "safari"]; let maybe_browser_list = results .runs .iter() .map(|x| order.iter().position(|target| *target == x.browser_name)) .collect::<Option<Vec<usize>>>(); if maybe_browser_list.is_none()
let browser_list = maybe_browser_list.unwrap(); writer.write_record([ "Test", "Firefox Failures", "Chrome Failures", "Safari Failures", "Bugs", ])?; for result in results.results.iter() { let mut scores = vec![String::new(), String::new(), String::new()]; for (output_idx, browser_idx) in browser_list.iter().enumerate() { if let Some(status) = result.legacy_status.get(*browser_idx) { if output_idx == 0 { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total)); } else { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total - status.passes)); } } } let mut bugs = BTreeSet::new(); if let Some(test_meta) = metadata.get(&result.test) { for metadata_entry in test_meta.iter() { if metadata_entry.product != "firefox" || !metadata_entry .url .starts_with("https://bugzilla.mozilla.org") { continue; } // For now add all bugs irrespective of status or subtest if let Ok(bug_url) = Url::parse(&metadata_entry.url) { if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") { bugs.insert(bug_id.into_owned()); } } } } let mut bugs_col = String::with_capacity(8 * bugs.len()); for bug in bugs.iter() { if !bugs_col.is_empty() { bugs_col.push(' '); } bugs_col.push_str(bug); } let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col]; writer.write_record(record)?; } Ok(()) } pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> { let mut columns = Vec::with_capacity(focus_areas.len()); for (name, data) in focus_areas.iter() { if data.counts_toward_score { columns.push(name.as_ref()); } } columns } fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> { let mut total_score: u64 = 0; for column in columns { let column = format!("{}-{}", browser, column); let score = row .get(&column) .ok_or_else(|| anyhow!("Failed to get column {}", column))?; let value: u64 = score .parse::<u64>() .map_err(|_| anyhow!("Failed to parse score"))?; total_score += value; } Ok(total_score as f64 / (10 * columns.len()) as f64) } pub fn write_browser_interop_scores( browsers: &[&str], scores: &[interop::ScoreRow], interop_2023_data: &interop::YearData, ) -> Result<()> { let browser_columns = interop_columns(&interop_2023_data.focus_areas); let data_path = Path::new("../docs/interop-2023/scores.csv"); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let mut headers = Vec::with_capacity(browsers.len() + 1); headers.push("date"); headers.extend_from_slice(browsers); writer.write_record(headers)?; let mut output: Vec<String> = Vec::with_capacity(browsers.len() + 1); for row in scores { output.resize(0, "".into()); output.push( row.get("date") .ok_or_else(|| anyhow!("Failed to read date"))? .into(), ); for browser in browsers { let score = browser_score(browser, &browser_columns, row)?; output.push(format!("{:.2}", score)) } writer.write_record(&output)?; } Ok(()) } pub fn run() -> Result<()> { let client = network::client(); let fyi = Wptfyi::new(None); let runs = get_run_data(&fyi, &client)?; let run_ids = latest_runs(&runs)? .iter() .map(|x| x.id) .collect::<Vec<i64>>(); let interop_data = get_interop_data(&fyi, &client)?; let interop_2023_data = interop_data .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 metadata"))?; let interop_categories = get_interop_categories(&fyi, &client)?; let interop_2023_categories = interop_categories .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 categories"))?; let categories_by_name = interop_2023_categories.by_name(); let metadata = get_metadata(&fyi, &client)?; for (name, focus_area) in interop_2023_data.focus_areas.iter() { write_focus_area( &fyi, &client, name, focus_area, &run_ids, &categories_by_name, &metadata, )?; } let scores = get_interop_scores(&fyi, &client, interop::BrowserChannel::Experimental)?; write_browser_interop_scores(&["firefox", "chrome", "safari"], &scores, interop_2023_data)?; Ok(()) }
{ return Err(anyhow!("Didn't get results for all three browsers")); }
conditional_block
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, LabelClause, NotClause, OrClause, Query, ResultClause}; use wptfyi::{interop, metadata, result, run, search, Wptfyi}; fn fx_failures_query(labels: &[&str]) -> Query { let pass_statuses = &[Status::Ok, Status::Pass]; let mut root_clause = AndClause { and: Vec::with_capacity(3), }; for status in pass_statuses.iter() { root_clause.push(Clause::Not(NotClause { not: Box::new(Clause::Result(ResultClause { browser_name: "firefox".to_owned(), status: status.clone(), })), })); } if !labels.is_empty() { let mut labels_clause = OrClause { or: Vec::with_capacity(labels.len()), }; for label in labels { labels_clause.push(Clause::Label(LabelClause { label: (*label).into(), })); } root_clause.push(Clause::Or(labels_clause)); } Query { query: Clause::And(root_clause), } } fn
(wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> { let mut runs = wptfyi.runs(); for product in ["chrome", "firefox", "safari"].iter() { runs.add_product(product, "experimental") } runs.add_label("master"); runs.set_max_count(100); Ok(run::parse(&get(client, &String::from(runs.url()), None)?)?) } fn get_metadata( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, Vec<MetadataEntry>>> { let mut metadata = wptfyi.metadata(); for product in ["firefox"].iter() { metadata.add_product(product) } Ok(metadata::parse(&get( client, &String::from(metadata.url()), None, )?)?) } pub fn get_fx_failures( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, run_ids: &[i64], labels: &[&str], ) -> Result<result::SearchData> { let mut search = wptfyi.search(); for product in ["chrome", "firefox", "safari"].iter() { search.add_product(product, "experimental") } search.set_query(run_ids, fx_failures_query(labels)); search.add_label("master"); Ok(search::parse(&post( client, &String::from(search.url()), None, search.body(), )?)?) } pub fn get_interop_data( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::YearData>> { let runs = wptfyi.interop_data(); Ok(interop::parse(&get( client, &String::from(runs.url()), None, )?)?) } pub fn get_interop_categories( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::Categories>> { Ok(interop::parse_categories(&get( client, &String::from(wptfyi.interop_categories().url()), None, )?)?) } pub fn get_interop_scores( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, browser_channel: interop::BrowserChannel, ) -> Result<Vec<interop::ScoreRow>> { Ok(interop::parse_scores(&get( client, &String::from(wptfyi.interop_scores(browser_channel).url()), None, )?)?) } fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> { let mut runs_by_commit = run::runs_by_commit(runs); let latest_rev = runs_by_commit .iter() .filter(|(_, value)| value.len() == 3) .max_by(|(_, value_1), (_, value_2)| { let date_1 = value_1.iter().map(|x| x.created_at).max(); let date_2 = value_2.iter().map(|x| x.created_at).max(); date_1.cmp(&date_2) }) .map(|(key, _)| key.clone()); latest_rev .and_then(|x| runs_by_commit.remove(&x)) .ok_or_else(|| anyhow!("Failed to find any complete runs")) } pub fn write_focus_area( fyi: &Wptfyi, client: &reqwest::blocking::Client, name: &str, focus_area: &FocusArea, run_ids: &[i64], categories_by_name: &BTreeMap<String, &Category>, metadata: &BTreeMap<String, Vec<MetadataEntry>>, ) -> Result<()> { if !focus_area.counts_toward_score { return Ok(()); } let labels = &categories_by_name .get(name) .ok_or_else(|| anyhow!("Didn't find category {}", name))? .labels; let path = format!("../docs/interop-2023/{}.csv", name); let data_path = Path::new(&path); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let results = get_fx_failures( &fyi, &client, &run_ids, &labels .iter() .filter_map(|x| { if x.starts_with("interop-") { Some(x.as_ref()) } else { None } }) .collect::<Vec<&str>>(), )?; let order = &["firefox", "chrome", "safari"]; let maybe_browser_list = results .runs .iter() .map(|x| order.iter().position(|target| *target == x.browser_name)) .collect::<Option<Vec<usize>>>(); if maybe_browser_list.is_none() { return Err(anyhow!("Didn't get results for all three browsers")); } let browser_list = maybe_browser_list.unwrap(); writer.write_record([ "Test", "Firefox Failures", "Chrome Failures", "Safari Failures", "Bugs", ])?; for result in results.results.iter() { let mut scores = vec![String::new(), String::new(), String::new()]; for (output_idx, browser_idx) in browser_list.iter().enumerate() { if let Some(status) = result.legacy_status.get(*browser_idx) { if output_idx == 0 { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total)); } else { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total - status.passes)); } } } let mut bugs = BTreeSet::new(); if let Some(test_meta) = metadata.get(&result.test) { for metadata_entry in test_meta.iter() { if metadata_entry.product != "firefox" || !metadata_entry .url .starts_with("https://bugzilla.mozilla.org") { continue; } // For now add all bugs irrespective of status or subtest if let Ok(bug_url) = Url::parse(&metadata_entry.url) { if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") { bugs.insert(bug_id.into_owned()); } } } } let mut bugs_col = String::with_capacity(8 * bugs.len()); for bug in bugs.iter() { if !bugs_col.is_empty() { bugs_col.push(' '); } bugs_col.push_str(bug); } let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col]; writer.write_record(record)?; } Ok(()) } pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> { let mut columns = Vec::with_capacity(focus_areas.len()); for (name, data) in focus_areas.iter() { if data.counts_toward_score { columns.push(name.as_ref()); } } columns } fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> { let mut total_score: u64 = 0; for column in columns { let column = format!("{}-{}", browser, column); let score = row .get(&column) .ok_or_else(|| anyhow!("Failed to get column {}", column))?; let value: u64 = score .parse::<u64>() .map_err(|_| anyhow!("Failed to parse score"))?; total_score += value; } Ok(total_score as f64 / (10 * columns.len()) as f64) } pub fn write_browser_interop_scores( browsers: &[&str], scores: &[interop::ScoreRow], interop_2023_data: &interop::YearData, ) -> Result<()> { let browser_columns = interop_columns(&interop_2023_data.focus_areas); let data_path = Path::new("../docs/interop-2023/scores.csv"); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let mut headers = Vec::with_capacity(browsers.len() + 1); headers.push("date"); headers.extend_from_slice(browsers); writer.write_record(headers)?; let mut output: Vec<String> = Vec::with_capacity(browsers.len() + 1); for row in scores { output.resize(0, "".into()); output.push( row.get("date") .ok_or_else(|| anyhow!("Failed to read date"))? .into(), ); for browser in browsers { let score = browser_score(browser, &browser_columns, row)?; output.push(format!("{:.2}", score)) } writer.write_record(&output)?; } Ok(()) } pub fn run() -> Result<()> { let client = network::client(); let fyi = Wptfyi::new(None); let runs = get_run_data(&fyi, &client)?; let run_ids = latest_runs(&runs)? .iter() .map(|x| x.id) .collect::<Vec<i64>>(); let interop_data = get_interop_data(&fyi, &client)?; let interop_2023_data = interop_data .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 metadata"))?; let interop_categories = get_interop_categories(&fyi, &client)?; let interop_2023_categories = interop_categories .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 categories"))?; let categories_by_name = interop_2023_categories.by_name(); let metadata = get_metadata(&fyi, &client)?; for (name, focus_area) in interop_2023_data.focus_areas.iter() { write_focus_area( &fyi, &client, name, focus_area, &run_ids, &categories_by_name, &metadata, )?; } let scores = get_interop_scores(&fyi, &client, interop::BrowserChannel::Experimental)?; write_browser_interop_scores(&["firefox", "chrome", "safari"], &scores, interop_2023_data)?; Ok(()) }
get_run_data
identifier_name
interop.rs
use crate::network::{self, get, post}; use anyhow::{anyhow, Result}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::Path; use url::Url; use wptfyi::interop::{Category, FocusArea}; use wptfyi::metadata::MetadataEntry; use wptfyi::result::Status; use wptfyi::search::{AndClause, Clause, LabelClause, NotClause, OrClause, Query, ResultClause}; use wptfyi::{interop, metadata, result, run, search, Wptfyi}; fn fx_failures_query(labels: &[&str]) -> Query { let pass_statuses = &[Status::Ok, Status::Pass]; let mut root_clause = AndClause { and: Vec::with_capacity(3), }; for status in pass_statuses.iter() { root_clause.push(Clause::Not(NotClause { not: Box::new(Clause::Result(ResultClause { browser_name: "firefox".to_owned(), status: status.clone(), })), })); } if !labels.is_empty() { let mut labels_clause = OrClause { or: Vec::with_capacity(labels.len()), }; for label in labels { labels_clause.push(Clause::Label(LabelClause { label: (*label).into(), })); } root_clause.push(Clause::Or(labels_clause)); } Query { query: Clause::And(root_clause), } } fn get_run_data(wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> { let mut runs = wptfyi.runs(); for product in ["chrome", "firefox", "safari"].iter() { runs.add_product(product, "experimental") } runs.add_label("master"); runs.set_max_count(100); Ok(run::parse(&get(client, &String::from(runs.url()), None)?)?) } fn get_metadata( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, Vec<MetadataEntry>>> { let mut metadata = wptfyi.metadata(); for product in ["firefox"].iter() { metadata.add_product(product) } Ok(metadata::parse(&get( client, &String::from(metadata.url()), None, )?)?) } pub fn get_fx_failures( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, run_ids: &[i64], labels: &[&str], ) -> Result<result::SearchData> { let mut search = wptfyi.search(); for product in ["chrome", "firefox", "safari"].iter() { search.add_product(product, "experimental") } search.set_query(run_ids, fx_failures_query(labels)); search.add_label("master"); Ok(search::parse(&post( client, &String::from(search.url()), None, search.body(), )?)?) } pub fn get_interop_data( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::YearData>> { let runs = wptfyi.interop_data(); Ok(interop::parse(&get( client, &String::from(runs.url()), None, )?)?) } pub fn get_interop_categories( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, ) -> Result<BTreeMap<String, interop::Categories>> { Ok(interop::parse_categories(&get( client, &String::from(wptfyi.interop_categories().url()), None, )?)?) } pub fn get_interop_scores( wptfyi: &Wptfyi, client: &reqwest::blocking::Client, browser_channel: interop::BrowserChannel, ) -> Result<Vec<interop::ScoreRow>> { Ok(interop::parse_scores(&get( client, &String::from(wptfyi.interop_scores(browser_channel).url()), None, )?)?) } fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> { let mut runs_by_commit = run::runs_by_commit(runs); let latest_rev = runs_by_commit .iter() .filter(|(_, value)| value.len() == 3) .max_by(|(_, value_1), (_, value_2)| { let date_1 = value_1.iter().map(|x| x.created_at).max(); let date_2 = value_2.iter().map(|x| x.created_at).max(); date_1.cmp(&date_2) }) .map(|(key, _)| key.clone()); latest_rev .and_then(|x| runs_by_commit.remove(&x)) .ok_or_else(|| anyhow!("Failed to find any complete runs")) } pub fn write_focus_area( fyi: &Wptfyi, client: &reqwest::blocking::Client, name: &str, focus_area: &FocusArea, run_ids: &[i64], categories_by_name: &BTreeMap<String, &Category>, metadata: &BTreeMap<String, Vec<MetadataEntry>>, ) -> Result<()> { if !focus_area.counts_toward_score { return Ok(()); } let labels = &categories_by_name .get(name) .ok_or_else(|| anyhow!("Didn't find category {}", name))? .labels; let path = format!("../docs/interop-2023/{}.csv", name); let data_path = Path::new(&path); let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let results = get_fx_failures( &fyi, &client, &run_ids, &labels .iter() .filter_map(|x| { if x.starts_with("interop-") { Some(x.as_ref()) } else { None } }) .collect::<Vec<&str>>(), )?; let order = &["firefox", "chrome", "safari"]; let maybe_browser_list = results .runs .iter() .map(|x| order.iter().position(|target| *target == x.browser_name)) .collect::<Option<Vec<usize>>>(); if maybe_browser_list.is_none() { return Err(anyhow!("Didn't get results for all three browsers")); } let browser_list = maybe_browser_list.unwrap(); writer.write_record([ "Test", "Firefox Failures", "Chrome Failures", "Safari Failures", "Bugs", ])?; for result in results.results.iter() { let mut scores = vec![String::new(), String::new(), String::new()]; for (output_idx, browser_idx) in browser_list.iter().enumerate() { if let Some(status) = result.legacy_status.get(*browser_idx) { if output_idx == 0 { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total)); } else { // For Firefox output the total as this is the number of failures scores[output_idx].push_str(&format!("{}", status.total - status.passes)); } } } let mut bugs = BTreeSet::new(); if let Some(test_meta) = metadata.get(&result.test) { for metadata_entry in test_meta.iter() { if metadata_entry.product != "firefox" || !metadata_entry .url .starts_with("https://bugzilla.mozilla.org") { continue; } // For now add all bugs irrespective of status or subtest if let Ok(bug_url) = Url::parse(&metadata_entry.url) { if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") { bugs.insert(bug_id.into_owned()); } } } } let mut bugs_col = String::with_capacity(8 * bugs.len()); for bug in bugs.iter() { if !bugs_col.is_empty() { bugs_col.push(' '); } bugs_col.push_str(bug); } let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col]; writer.write_record(record)?; } Ok(()) } pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> { let mut columns = Vec::with_capacity(focus_areas.len()); for (name, data) in focus_areas.iter() { if data.counts_toward_score { columns.push(name.as_ref()); } } columns } fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> { let mut total_score: u64 = 0; for column in columns { let column = format!("{}-{}", browser, column); let score = row .get(&column) .ok_or_else(|| anyhow!("Failed to get column {}", column))?; let value: u64 = score .parse::<u64>() .map_err(|_| anyhow!("Failed to parse score"))?; total_score += value; } Ok(total_score as f64 / (10 * columns.len()) as f64) } pub fn write_browser_interop_scores( browsers: &[&str], scores: &[interop::ScoreRow], interop_2023_data: &interop::YearData, ) -> Result<()> { let browser_columns = interop_columns(&interop_2023_data.focus_areas); let data_path = Path::new("../docs/interop-2023/scores.csv");
let out_f = File::create(data_path)?; let mut writer = csv::WriterBuilder::new() .quote_style(csv::QuoteStyle::NonNumeric) .from_writer(out_f); let mut headers = Vec::with_capacity(browsers.len() + 1); headers.push("date"); headers.extend_from_slice(browsers); writer.write_record(headers)?; let mut output: Vec<String> = Vec::with_capacity(browsers.len() + 1); for row in scores { output.resize(0, "".into()); output.push( row.get("date") .ok_or_else(|| anyhow!("Failed to read date"))? .into(), ); for browser in browsers { let score = browser_score(browser, &browser_columns, row)?; output.push(format!("{:.2}", score)) } writer.write_record(&output)?; } Ok(()) } pub fn run() -> Result<()> { let client = network::client(); let fyi = Wptfyi::new(None); let runs = get_run_data(&fyi, &client)?; let run_ids = latest_runs(&runs)? .iter() .map(|x| x.id) .collect::<Vec<i64>>(); let interop_data = get_interop_data(&fyi, &client)?; let interop_2023_data = interop_data .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 metadata"))?; let interop_categories = get_interop_categories(&fyi, &client)?; let interop_2023_categories = interop_categories .get("2023") .ok_or_else(|| anyhow!("Failed to get Interop-2023 categories"))?; let categories_by_name = interop_2023_categories.by_name(); let metadata = get_metadata(&fyi, &client)?; for (name, focus_area) in interop_2023_data.focus_areas.iter() { write_focus_area( &fyi, &client, name, focus_area, &run_ids, &categories_by_name, &metadata, )?; } let scores = get_interop_scores(&fyi, &client, interop::BrowserChannel::Experimental)?; write_browser_interop_scores(&["firefox", "chrome", "safari"], &scores, interop_2023_data)?; Ok(()) }
random_line_split
lambda-classes.js
// CODE here for your Lambda Classes /* ----- */ // Person Class // * First we need a Person class. This will be our `base-class` // * Person receives `name` `age` `location` `gender` all as props // * Person receives `speak` as a method. // * This method logs out a phrase `Hello my name is Fred, I am from Bedrock` where `name` and `location` are the object's own props class Person { constructor (personAttrs) { this.name = personAttrs.name; this.age = personAttrs.age; this.location = personAttrs.location; this.gender = personAttrs.gender; } speak () { return `Hello my name is ${this.name}, I am from ${this.location}`; } } // Instructor Class // * Now that we have a Person as our base class, we'll build our Instructor class. // * Instructor uses the same attributes that have been set up by Person // * Instructor has the following unique props: // * `specialty` what the Instructor is good at i.e. 'redux' // * `favLanguage` i.e. 'JavaScript, Python, Elm etc.' // * `catchPhrase` i.e. `Don't forget the homies` // * Instructor has the following methods: // * `demo` receives a `subject` string as an argument and logs out the phrase 'Today we are learning about {subject}' where subject is the param passed in. // * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}' class Instructor extends Person { constructor (instructorAttrs) { super (instructorAttrs); this.specialty = instructorAttrs.specialty; this.favLanguage = instructorAttrs.favLanguage; this.catchPhrase = instructorAttrs.catchPhrase; } demo (subject) { console.log(`Today we are learning about ${subject}`); } grade (student, subject) { console.log(`${student.name} receives a perfect score on ${subject}`); } popQuiz (student, subject) { const points = Math.ceil(Math.random() * 10); console.log(`${this.name} gives pop Quiz on ${subject}!`); if (Math.random() > .5){ console.log(`Good answer! ${student.name} receives ${points} points.`); student.grade += points; } else { console.log(`Back to the TK for you! ${student.name} is docked ${points} points.`); student.grade -= points; } } } // Student Class // * Now we need some students! // * Student uses the same attributes that have been set up by Person // * Student has the following unique props: // * `previousBackground` i.e. what the Student used to do before Lambda School // * `className` i.e. CS132 // * `favSubjects`. i.e. an array of the student's favorite subjects ['Html', 'CSS', 'JavaScript'] // * Student has the following methods: // * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one. // * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}` // * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}` class Student extends Person { constructor (studentAttrs) { super (studentAttrs); this.previousBackground = studentAttrs.previousBackground; this.className = studentAttrs.className; this.favSubjects = studentAttrs.favSubjects; // Array! this.grade = studentAttrs.grade; } listsSubjects () { for (const subject of this.favSubjects) { console.log(subject); } } PRAssignment (subject) { console.log(`${this.name} has submitted a PR for ${subject}`); } sprintChallenge (subject) { console.log(`${this.name} has begun sprint challenge on ${subject}`) } graduate () { if (this.grade > 70) { console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`); } else { console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`); } } } // Project Manager Class // * Now that we have instructors and students, we'd be nowhere without our PM's // * ProjectManagers are extensions of Instructors // * ProjectManagers have the following uniqe props: // * `gradClassName`: i.e. CS1 // * `favInstructor`: i.e. Sean // * ProjectManangers have the following Methods: // * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!​​​​​ // * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}` class ProjectManager extends Instructor { constructor (pmAttrs) { super (pmAttrs); this.gradClassName = pmAttrs.gradClassName; this.favInstructor = pmAttrs.favInstructor; } standUp (channel) { console.log(`${this.name} announces to ${channel}, @channel standy times!​​​​​`) } debugsCode (student, subject) { console.log(`${this.name} debugs ${student.name}'s code on ${subject}`) } } // Test classes // Keep track of who's here: let instructors = []; let pms = []; let students = []; // Instructors: const jimBob = new Instructor ({ name: 'JimBob', age: '35', location: 'SLC', gender: 'M', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'Let\'s take a 5-minute break!' }); instructors.push('jimBob'); const janeBeth = new Instructor ({ name: 'JaneBeth', age: '37', location: 'LA', gender: 'F', specialty: 'CS', favLanguage: 'C', catchPhrase: 'Let\'s take a 7-minute break!' }); instructors.push('janeBeth'); // Students: const lilRoy = new Student ({ name: 'LittleRoy', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 85 }); students.push('lilRoy'); const bigRae = new Student ({ name: 'Big Raylene', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 92 }); students.push('bigRae'); const thirdStudent = new Student ({ name: 'thirdStudent', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 70 }); students.push('thirdStudent'); const fourthStudent = new Student ({ name: 'fourthStudent', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 77 }); students.push('fourthStudent'); // Project Managers: const maryBeth = new ProjectManager ({ name: 'Mary Beth', age: '25', location: 'HOU', gender: 'F', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'You\'re all doing great!', gradClassName: 'FSW13', favInstructor: 'JimBob', }); pms.push('maryBeth'); const michaelBen = new ProjectManager ({ name: 'Michael Ben', age: '24', location: 'BR', gender: 'M', specialty: 'Backend', favLanguage: 'Ruby', catchPhrase: 'Keep it up y\'all!', gradClassName: 'FSW14', favInstructor: 'JaneBeth', }); pms.push('michaelBen'); // // Test that instances are working // // jimBob tests: // console.log(jimBob.name) // 'JimBob' // console.log(jimBob.age) // '35', // console.log(jimBob.location) // 'SLC',
// console.log(jimBob.favLanguage) // 'JavaScript', // console.log(jimBob.catchPhrase) // 'Let\'s take a 5-minute break!' // jimBob.demo('Banjo'); // jimBob.grade(bigRae, 'Banjo'); // // janeBeth tests: // console.log(janeBeth.name) // 'JaneBeth' // console.log(janeBeth.age) // '37', // console.log(janeBeth.location) // 'LA', // console.log(janeBeth.gender) // 'F', // console.log(janeBeth.specialty) // 'CS', // console.log(janeBeth.favLanguage) // 'C', // console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!' // janeBeth.demo('CS'); // janeBeth.grade(lilRoy, 'CS'); // // lilRoy tests: // console.log(lilRoy.name) //: 'LittleRoy', // console.log(lilRoy.age) //: '27', // console.log(lilRoy.location) //: 'NYC', // console.log(lilRoy.gender) //: 'M', // console.log(lilRoy.previousBackground) //: 'Carpentry', // console.log(lilRoy.className) //: 'FSW16', // console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods'] // lilRoy.listsSubjects(); // lilRoy.PRAssignment('JS-I'); // lilRoy.sprintChallenge('JavaScript'); // // bigRae tests: // console.log(bigRae.name) //: 'Big Raylene', // console.log(bigRae.age) //: '22', // console.log(bigRae.location) //: 'PDX', // console.log(bigRae.gender) //: 'F', // console.log(bigRae.previousBackground) //: 'Construction', // console.log(bigRae.className) //: 'DS1', // console.log(bigRae.favSubjects) //: ['Linear Algebra', 'Statistics', 'Python Lists'] // bigRae.listsSubjects(); // bigRae.PRAssignment('PY-I'); // bigRae.sprintChallenge('DescriptiveStatistics'); // // maryBeth tests: // console.log(maryBeth.name) //: 'Mary Beth', // console.log(maryBeth.age) //: '25', // console.log(maryBeth.location) //: 'HOU', // console.log(maryBeth.gender) //: 'F', // console.log(maryBeth.specialty) //: 'Frontend', // console.log(maryBeth.favLanguage) //: 'JavaScript', // console.log(maryBeth.catchPhrase) //: 'You\'re all doing great!', // console.log(maryBeth.gradClassName) //: 'FSW13', // console.log(maryBeth.favInstructor) //: 'JimBob',. // maryBeth.standUp('#fsw16'); // maryBeth.debugsCode(lilRoy, 'Arrays'); // // michaelBen tests: // console.log(michaelBen.name) //: 'Michael Ben', // console.log(michaelBen.age) //: '24', // console.log(michaelBen.location) //: 'BR', // console.log(michaelBen.gender) //: 'M', // console.log(michaelBen.specialty) //: 'Backend', // console.log(michaelBen.favLanguage) //: 'Ruby', // console.log(michaelBen.catchPhrase) //: 'Keep it up y\'all!', // console.log(michaelBen.gradClassName) //: 'FSW14', // console.log(michaelBen.favInstructor) //: 'JaneBeth', // michaelBen.standUp('#DS1'); // michaelBen.debugsCode(bigRae, 'Constructors'); // // Test grade attribute and popQuiz method // console.log(lilRoy.grade); // janeBeth.popQuiz(lilRoy, 'banjo'); // console.log(lilRoy.grade); // // Test graduate method // lilRoy.graduate(); // Use random selections from instructors, pms, and students to simulate a cohort for (let each of students) { console.log(`${eval(each).name} starts the final sprint with ${eval(each).grade}% grade.`) } for (let day = 0; day < 5; day++) { //choose a student and instructor for session, ending in pop quiz: randStudent = eval(students[Math.floor(Math.random() * students.length)]); randInstructor = eval(instructors[Math.floor(Math.random() * instructors.length)]); randPM = eval(pms[Math.floor(Math.random() * pms.length)]); //console.log(`Here is ${randInstructor.name} teaching for the day.`); randInstructor.popQuiz(randStudent, randInstructor.specialty); //console.log(`Here is ${randPM.name} doing standup.`); randPM.standUp('#FSW16'); randPM.popQuiz(randStudent, randPM.specialty); } for (let each of students) { console.log(`${eval(each).name} is now at the end of the final sprint.`) eval(each).graduate(); }
// console.log(jimBob.gender) // 'M', // console.log(jimBob.specialty) // 'Frontend',
random_line_split
lambda-classes.js
// CODE here for your Lambda Classes /* ----- */ // Person Class // * First we need a Person class. This will be our `base-class` // * Person receives `name` `age` `location` `gender` all as props // * Person receives `speak` as a method. // * This method logs out a phrase `Hello my name is Fred, I am from Bedrock` where `name` and `location` are the object's own props class Person { constructor (personAttrs) { this.name = personAttrs.name; this.age = personAttrs.age; this.location = personAttrs.location; this.gender = personAttrs.gender; } speak () { return `Hello my name is ${this.name}, I am from ${this.location}`; } } // Instructor Class // * Now that we have a Person as our base class, we'll build our Instructor class. // * Instructor uses the same attributes that have been set up by Person // * Instructor has the following unique props: // * `specialty` what the Instructor is good at i.e. 'redux' // * `favLanguage` i.e. 'JavaScript, Python, Elm etc.' // * `catchPhrase` i.e. `Don't forget the homies` // * Instructor has the following methods: // * `demo` receives a `subject` string as an argument and logs out the phrase 'Today we are learning about {subject}' where subject is the param passed in. // * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}' class Instructor extends Person { constructor (instructorAttrs) { super (instructorAttrs); this.specialty = instructorAttrs.specialty; this.favLanguage = instructorAttrs.favLanguage; this.catchPhrase = instructorAttrs.catchPhrase; } demo (subject) { console.log(`Today we are learning about ${subject}`); } grade (student, subject) { console.log(`${student.name} receives a perfect score on ${subject}`); } popQuiz (student, subject)
} // Student Class // * Now we need some students! // * Student uses the same attributes that have been set up by Person // * Student has the following unique props: // * `previousBackground` i.e. what the Student used to do before Lambda School // * `className` i.e. CS132 // * `favSubjects`. i.e. an array of the student's favorite subjects ['Html', 'CSS', 'JavaScript'] // * Student has the following methods: // * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one. // * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}` // * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}` class Student extends Person { constructor (studentAttrs) { super (studentAttrs); this.previousBackground = studentAttrs.previousBackground; this.className = studentAttrs.className; this.favSubjects = studentAttrs.favSubjects; // Array! this.grade = studentAttrs.grade; } listsSubjects () { for (const subject of this.favSubjects) { console.log(subject); } } PRAssignment (subject) { console.log(`${this.name} has submitted a PR for ${subject}`); } sprintChallenge (subject) { console.log(`${this.name} has begun sprint challenge on ${subject}`) } graduate () { if (this.grade > 70) { console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`); } else { console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`); } } } // Project Manager Class // * Now that we have instructors and students, we'd be nowhere without our PM's // * ProjectManagers are extensions of Instructors // * ProjectManagers have the following uniqe props: // * `gradClassName`: i.e. CS1 // * `favInstructor`: i.e. Sean // * ProjectManangers have the following Methods: // * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!​​​​​ // * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}` class ProjectManager extends Instructor { constructor (pmAttrs) { super (pmAttrs); this.gradClassName = pmAttrs.gradClassName; this.favInstructor = pmAttrs.favInstructor; } standUp (channel) { console.log(`${this.name} announces to ${channel}, @channel standy times!​​​​​`) } debugsCode (student, subject) { console.log(`${this.name} debugs ${student.name}'s code on ${subject}`) } } // Test classes // Keep track of who's here: let instructors = []; let pms = []; let students = []; // Instructors: const jimBob = new Instructor ({ name: 'JimBob', age: '35', location: 'SLC', gender: 'M', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'Let\'s take a 5-minute break!' }); instructors.push('jimBob'); const janeBeth = new Instructor ({ name: 'JaneBeth', age: '37', location: 'LA', gender: 'F', specialty: 'CS', favLanguage: 'C', catchPhrase: 'Let\'s take a 7-minute break!' }); instructors.push('janeBeth'); // Students: const lilRoy = new Student ({ name: 'LittleRoy', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 85 }); students.push('lilRoy'); const bigRae = new Student ({ name: 'Big Raylene', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 92 }); students.push('bigRae'); const thirdStudent = new Student ({ name: 'thirdStudent', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 70 }); students.push('thirdStudent'); const fourthStudent = new Student ({ name: 'fourthStudent', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 77 }); students.push('fourthStudent'); // Project Managers: const maryBeth = new ProjectManager ({ name: 'Mary Beth', age: '25', location: 'HOU', gender: 'F', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'You\'re all doing great!', gradClassName: 'FSW13', favInstructor: 'JimBob', }); pms.push('maryBeth'); const michaelBen = new ProjectManager ({ name: 'Michael Ben', age: '24', location: 'BR', gender: 'M', specialty: 'Backend', favLanguage: 'Ruby', catchPhrase: 'Keep it up y\'all!', gradClassName: 'FSW14', favInstructor: 'JaneBeth', }); pms.push('michaelBen'); // // Test that instances are working // // jimBob tests: // console.log(jimBob.name) // 'JimBob' // console.log(jimBob.age) // '35', // console.log(jimBob.location) // 'SLC', // console.log(jimBob.gender) // 'M', // console.log(jimBob.specialty) // 'Frontend', // console.log(jimBob.favLanguage) // 'JavaScript', // console.log(jimBob.catchPhrase) // 'Let\'s take a 5-minute break!' // jimBob.demo('Banjo'); // jimBob.grade(bigRae, 'Banjo'); // // janeBeth tests: // console.log(janeBeth.name) // 'JaneBeth' // console.log(janeBeth.age) // '37', // console.log(janeBeth.location) // 'LA', // console.log(janeBeth.gender) // 'F', // console.log(janeBeth.specialty) // 'CS', // console.log(janeBeth.favLanguage) // 'C', // console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!' // janeBeth.demo('CS'); // janeBeth.grade(lilRoy, 'CS'); // // lilRoy tests: // console.log(lilRoy.name) //: 'LittleRoy', // console.log(lilRoy.age) //: '27', // console.log(lilRoy.location) //: 'NYC', // console.log(lilRoy.gender) //: 'M', // console.log(lilRoy.previousBackground) //: 'Carpentry', // console.log(lilRoy.className) //: 'FSW16', // console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods'] // lilRoy.listsSubjects(); // lilRoy.PRAssignment('JS-I'); // lilRoy.sprintChallenge('JavaScript'); // // bigRae tests: // console.log(bigRae.name) //: 'Big Raylene', // console.log(bigRae.age) //: '22', // console.log(bigRae.location) //: 'PDX', // console.log(bigRae.gender) //: 'F', // console.log(bigRae.previousBackground) //: 'Construction', // console.log(bigRae.className) //: 'DS1', // console.log(bigRae.favSubjects) //: ['Linear Algebra', 'Statistics', 'Python Lists'] // bigRae.listsSubjects(); // bigRae.PRAssignment('PY-I'); // bigRae.sprintChallenge('DescriptiveStatistics'); // // maryBeth tests: // console.log(maryBeth.name) //: 'Mary Beth', // console.log(maryBeth.age) //: '25', // console.log(maryBeth.location) //: 'HOU', // console.log(maryBeth.gender) //: 'F', // console.log(maryBeth.specialty) //: 'Frontend', // console.log(maryBeth.favLanguage) //: 'JavaScript', // console.log(maryBeth.catchPhrase) //: 'You\'re all doing great!', // console.log(maryBeth.gradClassName) //: 'FSW13', // console.log(maryBeth.favInstructor) //: 'JimBob',. // maryBeth.standUp('#fsw16'); // maryBeth.debugsCode(lilRoy, 'Arrays'); // // michaelBen tests: // console.log(michaelBen.name) //: 'Michael Ben', // console.log(michaelBen.age) //: '24', // console.log(michaelBen.location) //: 'BR', // console.log(michaelBen.gender) //: 'M', // console.log(michaelBen.specialty) //: 'Backend', // console.log(michaelBen.favLanguage) //: 'Ruby', // console.log(michaelBen.catchPhrase) //: 'Keep it up y\'all!', // console.log(michaelBen.gradClassName) //: 'FSW14', // console.log(michaelBen.favInstructor) //: 'JaneBeth', // michaelBen.standUp('#DS1'); // michaelBen.debugsCode(bigRae, 'Constructors'); // // Test grade attribute and popQuiz method // console.log(lilRoy.grade); // janeBeth.popQuiz(lilRoy, 'banjo'); // console.log(lilRoy.grade); // // Test graduate method // lilRoy.graduate(); // Use random selections from instructors, pms, and students to simulate a cohort for (let each of students) { console.log(`${eval(each).name} starts the final sprint with ${eval(each).grade}% grade.`) } for (let day = 0; day < 5; day++) { //choose a student and instructor for session, ending in pop quiz: randStudent = eval(students[Math.floor(Math.random() * students.length)]); randInstructor = eval(instructors[Math.floor(Math.random() * instructors.length)]); randPM = eval(pms[Math.floor(Math.random() * pms.length)]); //console.log(`Here is ${randInstructor.name} teaching for the day.`); randInstructor.popQuiz(randStudent, randInstructor.specialty); //console.log(`Here is ${randPM.name} doing standup.`); randPM.standUp('#FSW16'); randPM.popQuiz(randStudent, randPM.specialty); } for (let each of students) { console.log(`${eval(each).name} is now at the end of the final sprint.`) eval(each).graduate(); }
{ const points = Math.ceil(Math.random() * 10); console.log(`${this.name} gives pop Quiz on ${subject}!`); if (Math.random() > .5){ console.log(`Good answer! ${student.name} receives ${points} points.`); student.grade += points; } else { console.log(`Back to the TK for you! ${student.name} is docked ${points} points.`); student.grade -= points; } }
identifier_body
lambda-classes.js
// CODE here for your Lambda Classes /* ----- */ // Person Class // * First we need a Person class. This will be our `base-class` // * Person receives `name` `age` `location` `gender` all as props // * Person receives `speak` as a method. // * This method logs out a phrase `Hello my name is Fred, I am from Bedrock` where `name` and `location` are the object's own props class Person { constructor (personAttrs) { this.name = personAttrs.name; this.age = personAttrs.age; this.location = personAttrs.location; this.gender = personAttrs.gender; } speak () { return `Hello my name is ${this.name}, I am from ${this.location}`; } } // Instructor Class // * Now that we have a Person as our base class, we'll build our Instructor class. // * Instructor uses the same attributes that have been set up by Person // * Instructor has the following unique props: // * `specialty` what the Instructor is good at i.e. 'redux' // * `favLanguage` i.e. 'JavaScript, Python, Elm etc.' // * `catchPhrase` i.e. `Don't forget the homies` // * Instructor has the following methods: // * `demo` receives a `subject` string as an argument and logs out the phrase 'Today we are learning about {subject}' where subject is the param passed in. // * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}' class Instructor extends Person { constructor (instructorAttrs) { super (instructorAttrs); this.specialty = instructorAttrs.specialty; this.favLanguage = instructorAttrs.favLanguage; this.catchPhrase = instructorAttrs.catchPhrase; } demo (subject) { console.log(`Today we are learning about ${subject}`); } grade (student, subject) { console.log(`${student.name} receives a perfect score on ${subject}`); } popQuiz (student, subject) { const points = Math.ceil(Math.random() * 10); console.log(`${this.name} gives pop Quiz on ${subject}!`); if (Math.random() > .5){ console.log(`Good answer! ${student.name} receives ${points} points.`); student.grade += points; } else { console.log(`Back to the TK for you! ${student.name} is docked ${points} points.`); student.grade -= points; } } } // Student Class // * Now we need some students! // * Student uses the same attributes that have been set up by Person // * Student has the following unique props: // * `previousBackground` i.e. what the Student used to do before Lambda School // * `className` i.e. CS132 // * `favSubjects`. i.e. an array of the student's favorite subjects ['Html', 'CSS', 'JavaScript'] // * Student has the following methods: // * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one. // * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}` // * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}` class Student extends Person { constructor (studentAttrs) { super (studentAttrs); this.previousBackground = studentAttrs.previousBackground; this.className = studentAttrs.className; this.favSubjects = studentAttrs.favSubjects; // Array! this.grade = studentAttrs.grade; } listsSubjects () { for (const subject of this.favSubjects) { console.log(subject); } } PRAssignment (subject) { console.log(`${this.name} has submitted a PR for ${subject}`); } sprintChallenge (subject) { console.log(`${this.name} has begun sprint challenge on ${subject}`) } graduate () { if (this.grade > 70) { console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`); } else { console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`); } } } // Project Manager Class // * Now that we have instructors and students, we'd be nowhere without our PM's // * ProjectManagers are extensions of Instructors // * ProjectManagers have the following uniqe props: // * `gradClassName`: i.e. CS1 // * `favInstructor`: i.e. Sean // * ProjectManangers have the following Methods: // * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!​​​​​ // * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}` class ProjectManager extends Instructor { constructo
{ super (pmAttrs); this.gradClassName = pmAttrs.gradClassName; this.favInstructor = pmAttrs.favInstructor; } standUp (channel) { console.log(`${this.name} announces to ${channel}, @channel standy times!​​​​​`) } debugsCode (student, subject) { console.log(`${this.name} debugs ${student.name}'s code on ${subject}`) } } // Test classes // Keep track of who's here: let instructors = []; let pms = []; let students = []; // Instructors: const jimBob = new Instructor ({ name: 'JimBob', age: '35', location: 'SLC', gender: 'M', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'Let\'s take a 5-minute break!' }); instructors.push('jimBob'); const janeBeth = new Instructor ({ name: 'JaneBeth', age: '37', location: 'LA', gender: 'F', specialty: 'CS', favLanguage: 'C', catchPhrase: 'Let\'s take a 7-minute break!' }); instructors.push('janeBeth'); // Students: const lilRoy = new Student ({ name: 'LittleRoy', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 85 }); students.push('lilRoy'); const bigRae = new Student ({ name: 'Big Raylene', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 92 }); students.push('bigRae'); const thirdStudent = new Student ({ name: 'thirdStudent', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 70 }); students.push('thirdStudent'); const fourthStudent = new Student ({ name: 'fourthStudent', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 77 }); students.push('fourthStudent'); // Project Managers: const maryBeth = new ProjectManager ({ name: 'Mary Beth', age: '25', location: 'HOU', gender: 'F', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'You\'re all doing great!', gradClassName: 'FSW13', favInstructor: 'JimBob', }); pms.push('maryBeth'); const michaelBen = new ProjectManager ({ name: 'Michael Ben', age: '24', location: 'BR', gender: 'M', specialty: 'Backend', favLanguage: 'Ruby', catchPhrase: 'Keep it up y\'all!', gradClassName: 'FSW14', favInstructor: 'JaneBeth', }); pms.push('michaelBen'); // // Test that instances are working // // jimBob tests: // console.log(jimBob.name) // 'JimBob' // console.log(jimBob.age) // '35', // console.log(jimBob.location) // 'SLC', // console.log(jimBob.gender) // 'M', // console.log(jimBob.specialty) // 'Frontend', // console.log(jimBob.favLanguage) // 'JavaScript', // console.log(jimBob.catchPhrase) // 'Let\'s take a 5-minute break!' // jimBob.demo('Banjo'); // jimBob.grade(bigRae, 'Banjo'); // // janeBeth tests: // console.log(janeBeth.name) // 'JaneBeth' // console.log(janeBeth.age) // '37', // console.log(janeBeth.location) // 'LA', // console.log(janeBeth.gender) // 'F', // console.log(janeBeth.specialty) // 'CS', // console.log(janeBeth.favLanguage) // 'C', // console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!' // janeBeth.demo('CS'); // janeBeth.grade(lilRoy, 'CS'); // // lilRoy tests: // console.log(lilRoy.name) //: 'LittleRoy', // console.log(lilRoy.age) //: '27', // console.log(lilRoy.location) //: 'NYC', // console.log(lilRoy.gender) //: 'M', // console.log(lilRoy.previousBackground) //: 'Carpentry', // console.log(lilRoy.className) //: 'FSW16', // console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods'] // lilRoy.listsSubjects(); // lilRoy.PRAssignment('JS-I'); // lilRoy.sprintChallenge('JavaScript'); // // bigRae tests: // console.log(bigRae.name) //: 'Big Raylene', // console.log(bigRae.age) //: '22', // console.log(bigRae.location) //: 'PDX', // console.log(bigRae.gender) //: 'F', // console.log(bigRae.previousBackground) //: 'Construction', // console.log(bigRae.className) //: 'DS1', // console.log(bigRae.favSubjects) //: ['Linear Algebra', 'Statistics', 'Python Lists'] // bigRae.listsSubjects(); // bigRae.PRAssignment('PY-I'); // bigRae.sprintChallenge('DescriptiveStatistics'); // // maryBeth tests: // console.log(maryBeth.name) //: 'Mary Beth', // console.log(maryBeth.age) //: '25', // console.log(maryBeth.location) //: 'HOU', // console.log(maryBeth.gender) //: 'F', // console.log(maryBeth.specialty) //: 'Frontend', // console.log(maryBeth.favLanguage) //: 'JavaScript', // console.log(maryBeth.catchPhrase) //: 'You\'re all doing great!', // console.log(maryBeth.gradClassName) //: 'FSW13', // console.log(maryBeth.favInstructor) //: 'JimBob',. // maryBeth.standUp('#fsw16'); // maryBeth.debugsCode(lilRoy, 'Arrays'); // // michaelBen tests: // console.log(michaelBen.name) //: 'Michael Ben', // console.log(michaelBen.age) //: '24', // console.log(michaelBen.location) //: 'BR', // console.log(michaelBen.gender) //: 'M', // console.log(michaelBen.specialty) //: 'Backend', // console.log(michaelBen.favLanguage) //: 'Ruby', // console.log(michaelBen.catchPhrase) //: 'Keep it up y\'all!', // console.log(michaelBen.gradClassName) //: 'FSW14', // console.log(michaelBen.favInstructor) //: 'JaneBeth', // michaelBen.standUp('#DS1'); // michaelBen.debugsCode(bigRae, 'Constructors'); // // Test grade attribute and popQuiz method // console.log(lilRoy.grade); // janeBeth.popQuiz(lilRoy, 'banjo'); // console.log(lilRoy.grade); // // Test graduate method // lilRoy.graduate(); // Use random selections from instructors, pms, and students to simulate a cohort for (let each of students) { console.log(`${eval(each).name} starts the final sprint with ${eval(each).grade}% grade.`) } for (let day = 0; day < 5; day++) { //choose a student and instructor for session, ending in pop quiz: randStudent = eval(students[Math.floor(Math.random() * students.length)]); randInstructor = eval(instructors[Math.floor(Math.random() * instructors.length)]); randPM = eval(pms[Math.floor(Math.random() * pms.length)]); //console.log(`Here is ${randInstructor.name} teaching for the day.`); randInstructor.popQuiz(randStudent, randInstructor.specialty); //console.log(`Here is ${randPM.name} doing standup.`); randPM.standUp('#FSW16'); randPM.popQuiz(randStudent, randPM.specialty); } for (let each of students) { console.log(`${eval(each).name} is now at the end of the final sprint.`) eval(each).graduate(); }
r (pmAttrs)
identifier_name
lambda-classes.js
// CODE here for your Lambda Classes /* ----- */ // Person Class // * First we need a Person class. This will be our `base-class` // * Person receives `name` `age` `location` `gender` all as props // * Person receives `speak` as a method. // * This method logs out a phrase `Hello my name is Fred, I am from Bedrock` where `name` and `location` are the object's own props class Person { constructor (personAttrs) { this.name = personAttrs.name; this.age = personAttrs.age; this.location = personAttrs.location; this.gender = personAttrs.gender; } speak () { return `Hello my name is ${this.name}, I am from ${this.location}`; } } // Instructor Class // * Now that we have a Person as our base class, we'll build our Instructor class. // * Instructor uses the same attributes that have been set up by Person // * Instructor has the following unique props: // * `specialty` what the Instructor is good at i.e. 'redux' // * `favLanguage` i.e. 'JavaScript, Python, Elm etc.' // * `catchPhrase` i.e. `Don't forget the homies` // * Instructor has the following methods: // * `demo` receives a `subject` string as an argument and logs out the phrase 'Today we are learning about {subject}' where subject is the param passed in. // * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}' class Instructor extends Person { constructor (instructorAttrs) { super (instructorAttrs); this.specialty = instructorAttrs.specialty; this.favLanguage = instructorAttrs.favLanguage; this.catchPhrase = instructorAttrs.catchPhrase; } demo (subject) { console.log(`Today we are learning about ${subject}`); } grade (student, subject) { console.log(`${student.name} receives a perfect score on ${subject}`); } popQuiz (student, subject) { const points = Math.ceil(Math.random() * 10); console.log(`${this.name} gives pop Quiz on ${subject}!`); if (Math.random() > .5){ console.log(`Good answer! ${student.name} receives ${points} points.`); student.grade += points; } else
} } // Student Class // * Now we need some students! // * Student uses the same attributes that have been set up by Person // * Student has the following unique props: // * `previousBackground` i.e. what the Student used to do before Lambda School // * `className` i.e. CS132 // * `favSubjects`. i.e. an array of the student's favorite subjects ['Html', 'CSS', 'JavaScript'] // * Student has the following methods: // * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one. // * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}` // * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}` class Student extends Person { constructor (studentAttrs) { super (studentAttrs); this.previousBackground = studentAttrs.previousBackground; this.className = studentAttrs.className; this.favSubjects = studentAttrs.favSubjects; // Array! this.grade = studentAttrs.grade; } listsSubjects () { for (const subject of this.favSubjects) { console.log(subject); } } PRAssignment (subject) { console.log(`${this.name} has submitted a PR for ${subject}`); } sprintChallenge (subject) { console.log(`${this.name} has begun sprint challenge on ${subject}`) } graduate () { if (this.grade > 70) { console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`); } else { console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`); } } } // Project Manager Class // * Now that we have instructors and students, we'd be nowhere without our PM's // * ProjectManagers are extensions of Instructors // * ProjectManagers have the following uniqe props: // * `gradClassName`: i.e. CS1 // * `favInstructor`: i.e. Sean // * ProjectManangers have the following Methods: // * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!​​​​​ // * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}` class ProjectManager extends Instructor { constructor (pmAttrs) { super (pmAttrs); this.gradClassName = pmAttrs.gradClassName; this.favInstructor = pmAttrs.favInstructor; } standUp (channel) { console.log(`${this.name} announces to ${channel}, @channel standy times!​​​​​`) } debugsCode (student, subject) { console.log(`${this.name} debugs ${student.name}'s code on ${subject}`) } } // Test classes // Keep track of who's here: let instructors = []; let pms = []; let students = []; // Instructors: const jimBob = new Instructor ({ name: 'JimBob', age: '35', location: 'SLC', gender: 'M', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'Let\'s take a 5-minute break!' }); instructors.push('jimBob'); const janeBeth = new Instructor ({ name: 'JaneBeth', age: '37', location: 'LA', gender: 'F', specialty: 'CS', favLanguage: 'C', catchPhrase: 'Let\'s take a 7-minute break!' }); instructors.push('janeBeth'); // Students: const lilRoy = new Student ({ name: 'LittleRoy', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 85 }); students.push('lilRoy'); const bigRae = new Student ({ name: 'Big Raylene', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 92 }); students.push('bigRae'); const thirdStudent = new Student ({ name: 'thirdStudent', age: '22', location: 'PDX', gender: 'F', previousBackground: 'Construction', className: 'DS1', favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'], grade: 70 }); students.push('thirdStudent'); const fourthStudent = new Student ({ name: 'fourthStudent', age: '27', location: 'NYC', gender: 'M', previousBackground: 'Carpentry', className: 'FSW16', favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'], grade: 77 }); students.push('fourthStudent'); // Project Managers: const maryBeth = new ProjectManager ({ name: 'Mary Beth', age: '25', location: 'HOU', gender: 'F', specialty: 'Frontend', favLanguage: 'JavaScript', catchPhrase: 'You\'re all doing great!', gradClassName: 'FSW13', favInstructor: 'JimBob', }); pms.push('maryBeth'); const michaelBen = new ProjectManager ({ name: 'Michael Ben', age: '24', location: 'BR', gender: 'M', specialty: 'Backend', favLanguage: 'Ruby', catchPhrase: 'Keep it up y\'all!', gradClassName: 'FSW14', favInstructor: 'JaneBeth', }); pms.push('michaelBen'); // // Test that instances are working // // jimBob tests: // console.log(jimBob.name) // 'JimBob' // console.log(jimBob.age) // '35', // console.log(jimBob.location) // 'SLC', // console.log(jimBob.gender) // 'M', // console.log(jimBob.specialty) // 'Frontend', // console.log(jimBob.favLanguage) // 'JavaScript', // console.log(jimBob.catchPhrase) // 'Let\'s take a 5-minute break!' // jimBob.demo('Banjo'); // jimBob.grade(bigRae, 'Banjo'); // // janeBeth tests: // console.log(janeBeth.name) // 'JaneBeth' // console.log(janeBeth.age) // '37', // console.log(janeBeth.location) // 'LA', // console.log(janeBeth.gender) // 'F', // console.log(janeBeth.specialty) // 'CS', // console.log(janeBeth.favLanguage) // 'C', // console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!' // janeBeth.demo('CS'); // janeBeth.grade(lilRoy, 'CS'); // // lilRoy tests: // console.log(lilRoy.name) //: 'LittleRoy', // console.log(lilRoy.age) //: '27', // console.log(lilRoy.location) //: 'NYC', // console.log(lilRoy.gender) //: 'M', // console.log(lilRoy.previousBackground) //: 'Carpentry', // console.log(lilRoy.className) //: 'FSW16', // console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods'] // lilRoy.listsSubjects(); // lilRoy.PRAssignment('JS-I'); // lilRoy.sprintChallenge('JavaScript'); // // bigRae tests: // console.log(bigRae.name) //: 'Big Raylene', // console.log(bigRae.age) //: '22', // console.log(bigRae.location) //: 'PDX', // console.log(bigRae.gender) //: 'F', // console.log(bigRae.previousBackground) //: 'Construction', // console.log(bigRae.className) //: 'DS1', // console.log(bigRae.favSubjects) //: ['Linear Algebra', 'Statistics', 'Python Lists'] // bigRae.listsSubjects(); // bigRae.PRAssignment('PY-I'); // bigRae.sprintChallenge('DescriptiveStatistics'); // // maryBeth tests: // console.log(maryBeth.name) //: 'Mary Beth', // console.log(maryBeth.age) //: '25', // console.log(maryBeth.location) //: 'HOU', // console.log(maryBeth.gender) //: 'F', // console.log(maryBeth.specialty) //: 'Frontend', // console.log(maryBeth.favLanguage) //: 'JavaScript', // console.log(maryBeth.catchPhrase) //: 'You\'re all doing great!', // console.log(maryBeth.gradClassName) //: 'FSW13', // console.log(maryBeth.favInstructor) //: 'JimBob',. // maryBeth.standUp('#fsw16'); // maryBeth.debugsCode(lilRoy, 'Arrays'); // // michaelBen tests: // console.log(michaelBen.name) //: 'Michael Ben', // console.log(michaelBen.age) //: '24', // console.log(michaelBen.location) //: 'BR', // console.log(michaelBen.gender) //: 'M', // console.log(michaelBen.specialty) //: 'Backend', // console.log(michaelBen.favLanguage) //: 'Ruby', // console.log(michaelBen.catchPhrase) //: 'Keep it up y\'all!', // console.log(michaelBen.gradClassName) //: 'FSW14', // console.log(michaelBen.favInstructor) //: 'JaneBeth', // michaelBen.standUp('#DS1'); // michaelBen.debugsCode(bigRae, 'Constructors'); // // Test grade attribute and popQuiz method // console.log(lilRoy.grade); // janeBeth.popQuiz(lilRoy, 'banjo'); // console.log(lilRoy.grade); // // Test graduate method // lilRoy.graduate(); // Use random selections from instructors, pms, and students to simulate a cohort for (let each of students) { console.log(`${eval(each).name} starts the final sprint with ${eval(each).grade}% grade.`) } for (let day = 0; day < 5; day++) { //choose a student and instructor for session, ending in pop quiz: randStudent = eval(students[Math.floor(Math.random() * students.length)]); randInstructor = eval(instructors[Math.floor(Math.random() * instructors.length)]); randPM = eval(pms[Math.floor(Math.random() * pms.length)]); //console.log(`Here is ${randInstructor.name} teaching for the day.`); randInstructor.popQuiz(randStudent, randInstructor.specialty); //console.log(`Here is ${randPM.name} doing standup.`); randPM.standUp('#FSW16'); randPM.popQuiz(randStudent, randPM.specialty); } for (let each of students) { console.log(`${eval(each).name} is now at the end of the final sprint.`) eval(each).graduate(); }
{ console.log(`Back to the TK for you! ${student.name} is docked ${points} points.`); student.grade -= points; }
conditional_block
disk.py
# Wizard Kit: Functions - Disk from functions.common import * from settings.partition_uids import * # Regex REGEX_BAD_PARTITION = re.compile(r'(RAW|Unknown)', re.IGNORECASE) REGEX_DISK_GPT = re.compile( r'Disk ID: {[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+}', re.IGNORECASE) REGEX_DISK_MBR = re.compile(r'Disk ID: [A-Z0-9]+', re.IGNORECASE) REGEX_DISK_RAW = re.compile(r'Disk ID: 00000000', re.IGNORECASE) def assign_volume_letters(): """Assign a volume letter to all available volumes.""" remove_volume_letters() # Write script script = [] for vol in get_volumes(): script.append('select volume {}'.format(vol['Number'])) script.append('assign') # Run run_diskpart(script) def get_boot_mode(): """Check if the boot mode was UEFI or legacy.""" boot_mode = 'Legacy' try: reg_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control') reg_value = winreg.QueryValueEx(reg_key, 'PEFirmwareType')[0] if reg_value == 2: boot_mode = 'UEFI' except: boot_mode = 'Unknown' return boot_mode def get_disk_details(disk): """Get disk details using DiskPart.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'detail disk'] # Run try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Set disk name details['Name'] = tmp[4] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) return details def get_disks(): """Get list of attached disks using DiskPart.""" disks = [] try: # Run script result = run_diskpart(['list disk']) except subprocess.CalledProcessError: pass else: # Append disk numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Disk (\d+)\s+\w+\s+(\d+\s+\w+)', output): num = tmp[0] size = human_readable_size(tmp[1]) disks.append({'Number': num, 'Size': size}) return disks def get_partition_details(disk, partition): """Get partition details using DiskPart and fsutil.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'select partition {}'.format(partition['Number']), 'detail partition'] # Diskpart details try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Get volume letter or RAW status output = result.stdout.decode().strip() tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output) if tmp: if tmp.group(1).upper() == 'RAW': details['FileSystem'] = RAW else: details['Letter'] = tmp.group(1) # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Get MBR type / GPT GUID for extra details on "Unknown" partitions guid = PARTITION_UIDS.get(details.get('Type').upper(), {}) if guid: details.update({ 'Description': guid.get('Description', '')[:29], 'OS': guid.get('OS', 'Unknown')[:27]}) if 'Letter' in details: # Disk usage try: tmp = psutil.disk_usage('{}:\\'.format(details['Letter'])) except OSError as err: details['FileSystem'] = 'Unknown' details['Error'] = err.strerror else: details['Used Space'] = human_readable_size(tmp.used) # fsutil details cmd = [ 'fsutil', 'fsinfo', 'volumeinfo', '{}:'.format(details['Letter']) ] try: result = run_program(cmd) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Add "Feature" lines details['File System Features'] = [s.strip() for s in tmp if ':' not in s] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Set Volume Name details['Name'] = details.get('Volume Name', '') # Set FileSystem Type if details.get('FileSystem', '') not in ['RAW', 'Unknown']: details['FileSystem'] = details.get('File System Name', 'Unknown') return details def get_partitions(disk): """Get list of partition using DiskPart.""" partitions = [] script = [ 'select disk {}'.format(disk['Number']), 'list partition'] try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Append partition numbers output = result.stdout.decode().strip() regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+' for tmp in re.findall(regex, output, re.IGNORECASE): num = tmp[0] size = human_readable_size(tmp[1]) partitions.append({'Number': num, 'Size': size}) return partitions def get_table_type(disk): """Get disk partition table type using DiskPart.""" part_type = 'Unknown' script = [ 'select disk {}'.format(disk['Number']), 'uniqueid disk'] try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() if REGEX_DISK_GPT.search(output): part_type = 'GPT' elif REGEX_DISK_MBR.search(output): part_type = 'MBR' elif REGEX_DISK_RAW.search(output): part_type = 'RAW' return part_type def get_volumes(): """Get list of volumes using DiskPart.""" vols = [] try: result = run_diskpart(['list volume']) except subprocess.CalledProcessError: pass else: # Append volume numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output): vols.append({'Number': tmp[0], 'Letter': tmp[1]}) return vols def is_bad_partition(par): """Check if the partition is accessible.""" return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem']) def prep_disk_for_formatting(disk=None): """Gather details about the disk and its partitions.""" disk['Format Warnings'] = '\n' width = len(str(len(disk['Partitions']))) # Bail early if disk is None: raise Exception('Disk not provided.') # Set boot method and partition table type disk['Use GPT'] = True if (get_boot_mode() == 'UEFI'): if (not ask("Setup Windows to use UEFI booting?")): disk['Use GPT'] = False else: if (ask("Setup Windows to use BIOS/Legacy booting?")): disk['Use GPT'] = False # Set Display and Warning Strings if len(disk['Partitions']) == 0: disk['Format Warnings'] += 'No partitions found\n' for partition in disk['Partitions']: display = '{size} {fs}'.format( num = partition['Number'], width = width, size = partition['Size'], fs = partition['FileSystem']) if is_bad_partition(partition): # Set display string using partition description & OS type display += '\t\t{q}{name}{q}\t{desc} ({os})'.format( display = display, q = '"' if partition['Name'] != '' else '', name = partition['Name'], desc = partition['Description'], os = partition['OS']) else: # List space used instead of partition description & OS type display += ' (Used: {used})\t{q}{name}{q}'.format( used = partition['Used Space'], q = '"' if partition['Name'] != '' else '', name = partition['Name']) # For all partitions partition['Display String'] = display def reassign_volume_letter(letter, new_letter='I'): """Assign a new letter to a volume using DiskPart.""" if not letter: # Ignore return None script = [ 'select volume {}'.format(letter), 'remove noerr', 'assign letter={}'.format(new_letter)] try: run_diskpart(script) except subprocess.CalledProcessError: pass else: return new_letter def remove_volume_letters(keep=None): """Remove all assigned volume letters using DiskPart.""" if not keep: keep = '' script = [] for vol in get_volumes(): if vol['Letter'].upper() != keep.upper(): script.append('select volume {}'.format(vol['Number'])) script.append('remove noerr') # Run script try: run_diskpart(script) except subprocess.CalledProcessError: pass def run_diskpart(script): """Run DiskPart script.""" tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP']) # Write script with open(tempfile, 'w') as f: for line in script: f.write('{}\n'.format(line)) # Run script cmd = [ r'{}\Windows\System32\diskpart.exe'.format( global_vars['Env']['SYSTEMDRIVE']), '/s', tempfile] result = run_program(cmd) sleep(2) return result
# Get disk details for disk in disks: # Get partition style disk['Table'] = get_table_type(disk) # Get disk name/model and physical details disk.update(get_disk_details(disk)) # Get partition info for disk disk['Partitions'] = get_partitions(disk) for partition in disk['Partitions']: # Get partition details partition.update(get_partition_details(disk, partition)) # Done return disks def select_disk(title='Which disk?', disks=[]): """Select a disk from the attached disks""" # Build menu disk_options = [] for disk in disks: display_name = '{}\t[{}] ({}) {}'.format( disk.get('Size', ''), disk.get('Table', ''), disk.get('Type', ''), disk.get('Name', 'Unknown'), ) pwidth=len(str(len(disk['Partitions']))) for partition in disk['Partitions']: # Main text p_name = 'Partition {num:>{width}}: {size} ({fs})'.format( num = partition['Number'], width = pwidth, size = partition['Size'], fs = partition['FileSystem']) if partition['Name']: p_name += '\t"{}"'.format(partition['Name']) # Show unsupported partition(s) if is_bad_partition(partition): p_name = '{YELLOW}{p_name}{CLEAR}'.format( p_name=p_name, **COLORS) display_name += '\n\t\t\t{}'.format(p_name) if not disk['Partitions']: display_name += '\n\t\t\t{}No partitions found.{}'.format( COLORS['YELLOW'], COLORS['CLEAR']) disk_options.append({'Name': display_name, 'Disk': disk}) actions = [ {'Name': 'Main Menu', 'Letter': 'M'}, ] # Menu loop selection = menu_select( title = title, main_entries = disk_options, action_entries = actions) if (selection.isnumeric()): return disk_options[int(selection)-1]['Disk'] elif (selection == 'M'): raise GenericAbort if __name__ == '__main__': print("This file is not meant to be called directly.") # vim: sts=2 sw=2 ts=2
def scan_disks(): """Get details about the attached disks""" disks = get_disks()
random_line_split
disk.py
# Wizard Kit: Functions - Disk from functions.common import * from settings.partition_uids import * # Regex REGEX_BAD_PARTITION = re.compile(r'(RAW|Unknown)', re.IGNORECASE) REGEX_DISK_GPT = re.compile( r'Disk ID: {[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+}', re.IGNORECASE) REGEX_DISK_MBR = re.compile(r'Disk ID: [A-Z0-9]+', re.IGNORECASE) REGEX_DISK_RAW = re.compile(r'Disk ID: 00000000', re.IGNORECASE) def assign_volume_letters(): """Assign a volume letter to all available volumes.""" remove_volume_letters() # Write script script = [] for vol in get_volumes(): script.append('select volume {}'.format(vol['Number'])) script.append('assign') # Run run_diskpart(script) def get_boot_mode(): """Check if the boot mode was UEFI or legacy.""" boot_mode = 'Legacy' try: reg_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control') reg_value = winreg.QueryValueEx(reg_key, 'PEFirmwareType')[0] if reg_value == 2: boot_mode = 'UEFI' except: boot_mode = 'Unknown' return boot_mode def get_disk_details(disk): """Get disk details using DiskPart.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'detail disk'] # Run try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Set disk name details['Name'] = tmp[4] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) return details def get_disks(): """Get list of attached disks using DiskPart.""" disks = [] try: # Run script result = run_diskpart(['list disk']) except subprocess.CalledProcessError: pass else: # Append disk numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Disk (\d+)\s+\w+\s+(\d+\s+\w+)', output): num = tmp[0] size = human_readable_size(tmp[1]) disks.append({'Number': num, 'Size': size}) return disks def get_partition_details(disk, partition): """Get partition details using DiskPart and fsutil.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'select partition {}'.format(partition['Number']), 'detail partition'] # Diskpart details try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Get volume letter or RAW status output = result.stdout.decode().strip() tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output) if tmp: if tmp.group(1).upper() == 'RAW': details['FileSystem'] = RAW else: details['Letter'] = tmp.group(1) # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Get MBR type / GPT GUID for extra details on "Unknown" partitions guid = PARTITION_UIDS.get(details.get('Type').upper(), {}) if guid: details.update({ 'Description': guid.get('Description', '')[:29], 'OS': guid.get('OS', 'Unknown')[:27]}) if 'Letter' in details: # Disk usage try: tmp = psutil.disk_usage('{}:\\'.format(details['Letter'])) except OSError as err: details['FileSystem'] = 'Unknown' details['Error'] = err.strerror else: details['Used Space'] = human_readable_size(tmp.used) # fsutil details cmd = [ 'fsutil', 'fsinfo', 'volumeinfo', '{}:'.format(details['Letter']) ] try: result = run_program(cmd) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Add "Feature" lines details['File System Features'] = [s.strip() for s in tmp if ':' not in s] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Set Volume Name details['Name'] = details.get('Volume Name', '') # Set FileSystem Type if details.get('FileSystem', '') not in ['RAW', 'Unknown']: details['FileSystem'] = details.get('File System Name', 'Unknown') return details def get_partitions(disk): """Get list of partition using DiskPart.""" partitions = [] script = [ 'select disk {}'.format(disk['Number']), 'list partition'] try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Append partition numbers output = result.stdout.decode().strip() regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+' for tmp in re.findall(regex, output, re.IGNORECASE): num = tmp[0] size = human_readable_size(tmp[1]) partitions.append({'Number': num, 'Size': size}) return partitions def get_table_type(disk): """Get disk partition table type using DiskPart.""" part_type = 'Unknown' script = [ 'select disk {}'.format(disk['Number']), 'uniqueid disk'] try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() if REGEX_DISK_GPT.search(output): part_type = 'GPT' elif REGEX_DISK_MBR.search(output): part_type = 'MBR' elif REGEX_DISK_RAW.search(output): part_type = 'RAW' return part_type def get_volumes(): """Get list of volumes using DiskPart.""" vols = [] try: result = run_diskpart(['list volume']) except subprocess.CalledProcessError: pass else: # Append volume numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output): vols.append({'Number': tmp[0], 'Letter': tmp[1]}) return vols def is_bad_partition(par): """Check if the partition is accessible.""" return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem']) def prep_disk_for_formatting(disk=None): """Gather details about the disk and its partitions.""" disk['Format Warnings'] = '\n' width = len(str(len(disk['Partitions']))) # Bail early if disk is None: raise Exception('Disk not provided.') # Set boot method and partition table type disk['Use GPT'] = True if (get_boot_mode() == 'UEFI'): if (not ask("Setup Windows to use UEFI booting?")): disk['Use GPT'] = False else: if (ask("Setup Windows to use BIOS/Legacy booting?")): disk['Use GPT'] = False # Set Display and Warning Strings if len(disk['Partitions']) == 0: disk['Format Warnings'] += 'No partitions found\n' for partition in disk['Partitions']: display = '{size} {fs}'.format( num = partition['Number'], width = width, size = partition['Size'], fs = partition['FileSystem']) if is_bad_partition(partition): # Set display string using partition description & OS type display += '\t\t{q}{name}{q}\t{desc} ({os})'.format( display = display, q = '"' if partition['Name'] != '' else '', name = partition['Name'], desc = partition['Description'], os = partition['OS']) else: # List space used instead of partition description & OS type display += ' (Used: {used})\t{q}{name}{q}'.format( used = partition['Used Space'], q = '"' if partition['Name'] != '' else '', name = partition['Name']) # For all partitions partition['Display String'] = display def reassign_volume_letter(letter, new_letter='I'):
def remove_volume_letters(keep=None): """Remove all assigned volume letters using DiskPart.""" if not keep: keep = '' script = [] for vol in get_volumes(): if vol['Letter'].upper() != keep.upper(): script.append('select volume {}'.format(vol['Number'])) script.append('remove noerr') # Run script try: run_diskpart(script) except subprocess.CalledProcessError: pass def run_diskpart(script): """Run DiskPart script.""" tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP']) # Write script with open(tempfile, 'w') as f: for line in script: f.write('{}\n'.format(line)) # Run script cmd = [ r'{}\Windows\System32\diskpart.exe'.format( global_vars['Env']['SYSTEMDRIVE']), '/s', tempfile] result = run_program(cmd) sleep(2) return result def scan_disks(): """Get details about the attached disks""" disks = get_disks() # Get disk details for disk in disks: # Get partition style disk['Table'] = get_table_type(disk) # Get disk name/model and physical details disk.update(get_disk_details(disk)) # Get partition info for disk disk['Partitions'] = get_partitions(disk) for partition in disk['Partitions']: # Get partition details partition.update(get_partition_details(disk, partition)) # Done return disks def select_disk(title='Which disk?', disks=[]): """Select a disk from the attached disks""" # Build menu disk_options = [] for disk in disks: display_name = '{}\t[{}] ({}) {}'.format( disk.get('Size', ''), disk.get('Table', ''), disk.get('Type', ''), disk.get('Name', 'Unknown'), ) pwidth=len(str(len(disk['Partitions']))) for partition in disk['Partitions']: # Main text p_name = 'Partition {num:>{width}}: {size} ({fs})'.format( num = partition['Number'], width = pwidth, size = partition['Size'], fs = partition['FileSystem']) if partition['Name']: p_name += '\t"{}"'.format(partition['Name']) # Show unsupported partition(s) if is_bad_partition(partition): p_name = '{YELLOW}{p_name}{CLEAR}'.format( p_name=p_name, **COLORS) display_name += '\n\t\t\t{}'.format(p_name) if not disk['Partitions']: display_name += '\n\t\t\t{}No partitions found.{}'.format( COLORS['YELLOW'], COLORS['CLEAR']) disk_options.append({'Name': display_name, 'Disk': disk}) actions = [ {'Name': 'Main Menu', 'Letter': 'M'}, ] # Menu loop selection = menu_select( title = title, main_entries = disk_options, action_entries = actions) if (selection.isnumeric()): return disk_options[int(selection)-1]['Disk'] elif (selection == 'M'): raise GenericAbort if __name__ == '__main__': print("This file is not meant to be called directly.") # vim: sts=2 sw=2 ts=2
"""Assign a new letter to a volume using DiskPart.""" if not letter: # Ignore return None script = [ 'select volume {}'.format(letter), 'remove noerr', 'assign letter={}'.format(new_letter)] try: run_diskpart(script) except subprocess.CalledProcessError: pass else: return new_letter
identifier_body
disk.py
# Wizard Kit: Functions - Disk from functions.common import * from settings.partition_uids import * # Regex REGEX_BAD_PARTITION = re.compile(r'(RAW|Unknown)', re.IGNORECASE) REGEX_DISK_GPT = re.compile( r'Disk ID: {[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+}', re.IGNORECASE) REGEX_DISK_MBR = re.compile(r'Disk ID: [A-Z0-9]+', re.IGNORECASE) REGEX_DISK_RAW = re.compile(r'Disk ID: 00000000', re.IGNORECASE) def assign_volume_letters(): """Assign a volume letter to all available volumes.""" remove_volume_letters() # Write script script = [] for vol in get_volumes(): script.append('select volume {}'.format(vol['Number'])) script.append('assign') # Run run_diskpart(script) def get_boot_mode(): """Check if the boot mode was UEFI or legacy.""" boot_mode = 'Legacy' try: reg_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control') reg_value = winreg.QueryValueEx(reg_key, 'PEFirmwareType')[0] if reg_value == 2: boot_mode = 'UEFI' except: boot_mode = 'Unknown' return boot_mode def get_disk_details(disk): """Get disk details using DiskPart.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'detail disk'] # Run try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Set disk name details['Name'] = tmp[4] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) return details def get_disks(): """Get list of attached disks using DiskPart.""" disks = [] try: # Run script result = run_diskpart(['list disk']) except subprocess.CalledProcessError: pass else: # Append disk numbers
return disks def get_partition_details(disk, partition): """Get partition details using DiskPart and fsutil.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'select partition {}'.format(partition['Number']), 'detail partition'] # Diskpart details try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Get volume letter or RAW status output = result.stdout.decode().strip() tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output) if tmp: if tmp.group(1).upper() == 'RAW': details['FileSystem'] = RAW else: details['Letter'] = tmp.group(1) # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Get MBR type / GPT GUID for extra details on "Unknown" partitions guid = PARTITION_UIDS.get(details.get('Type').upper(), {}) if guid: details.update({ 'Description': guid.get('Description', '')[:29], 'OS': guid.get('OS', 'Unknown')[:27]}) if 'Letter' in details: # Disk usage try: tmp = psutil.disk_usage('{}:\\'.format(details['Letter'])) except OSError as err: details['FileSystem'] = 'Unknown' details['Error'] = err.strerror else: details['Used Space'] = human_readable_size(tmp.used) # fsutil details cmd = [ 'fsutil', 'fsinfo', 'volumeinfo', '{}:'.format(details['Letter']) ] try: result = run_program(cmd) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Add "Feature" lines details['File System Features'] = [s.strip() for s in tmp if ':' not in s] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Set Volume Name details['Name'] = details.get('Volume Name', '') # Set FileSystem Type if details.get('FileSystem', '') not in ['RAW', 'Unknown']: details['FileSystem'] = details.get('File System Name', 'Unknown') return details def get_partitions(disk): """Get list of partition using DiskPart.""" partitions = [] script = [ 'select disk {}'.format(disk['Number']), 'list partition'] try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Append partition numbers output = result.stdout.decode().strip() regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+' for tmp in re.findall(regex, output, re.IGNORECASE): num = tmp[0] size = human_readable_size(tmp[1]) partitions.append({'Number': num, 'Size': size}) return partitions def get_table_type(disk): """Get disk partition table type using DiskPart.""" part_type = 'Unknown' script = [ 'select disk {}'.format(disk['Number']), 'uniqueid disk'] try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() if REGEX_DISK_GPT.search(output): part_type = 'GPT' elif REGEX_DISK_MBR.search(output): part_type = 'MBR' elif REGEX_DISK_RAW.search(output): part_type = 'RAW' return part_type def get_volumes(): """Get list of volumes using DiskPart.""" vols = [] try: result = run_diskpart(['list volume']) except subprocess.CalledProcessError: pass else: # Append volume numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output): vols.append({'Number': tmp[0], 'Letter': tmp[1]}) return vols def is_bad_partition(par): """Check if the partition is accessible.""" return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem']) def prep_disk_for_formatting(disk=None): """Gather details about the disk and its partitions.""" disk['Format Warnings'] = '\n' width = len(str(len(disk['Partitions']))) # Bail early if disk is None: raise Exception('Disk not provided.') # Set boot method and partition table type disk['Use GPT'] = True if (get_boot_mode() == 'UEFI'): if (not ask("Setup Windows to use UEFI booting?")): disk['Use GPT'] = False else: if (ask("Setup Windows to use BIOS/Legacy booting?")): disk['Use GPT'] = False # Set Display and Warning Strings if len(disk['Partitions']) == 0: disk['Format Warnings'] += 'No partitions found\n' for partition in disk['Partitions']: display = '{size} {fs}'.format( num = partition['Number'], width = width, size = partition['Size'], fs = partition['FileSystem']) if is_bad_partition(partition): # Set display string using partition description & OS type display += '\t\t{q}{name}{q}\t{desc} ({os})'.format( display = display, q = '"' if partition['Name'] != '' else '', name = partition['Name'], desc = partition['Description'], os = partition['OS']) else: # List space used instead of partition description & OS type display += ' (Used: {used})\t{q}{name}{q}'.format( used = partition['Used Space'], q = '"' if partition['Name'] != '' else '', name = partition['Name']) # For all partitions partition['Display String'] = display def reassign_volume_letter(letter, new_letter='I'): """Assign a new letter to a volume using DiskPart.""" if not letter: # Ignore return None script = [ 'select volume {}'.format(letter), 'remove noerr', 'assign letter={}'.format(new_letter)] try: run_diskpart(script) except subprocess.CalledProcessError: pass else: return new_letter def remove_volume_letters(keep=None): """Remove all assigned volume letters using DiskPart.""" if not keep: keep = '' script = [] for vol in get_volumes(): if vol['Letter'].upper() != keep.upper(): script.append('select volume {}'.format(vol['Number'])) script.append('remove noerr') # Run script try: run_diskpart(script) except subprocess.CalledProcessError: pass def run_diskpart(script): """Run DiskPart script.""" tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP']) # Write script with open(tempfile, 'w') as f: for line in script: f.write('{}\n'.format(line)) # Run script cmd = [ r'{}\Windows\System32\diskpart.exe'.format( global_vars['Env']['SYSTEMDRIVE']), '/s', tempfile] result = run_program(cmd) sleep(2) return result def scan_disks(): """Get details about the attached disks""" disks = get_disks() # Get disk details for disk in disks: # Get partition style disk['Table'] = get_table_type(disk) # Get disk name/model and physical details disk.update(get_disk_details(disk)) # Get partition info for disk disk['Partitions'] = get_partitions(disk) for partition in disk['Partitions']: # Get partition details partition.update(get_partition_details(disk, partition)) # Done return disks def select_disk(title='Which disk?', disks=[]): """Select a disk from the attached disks""" # Build menu disk_options = [] for disk in disks: display_name = '{}\t[{}] ({}) {}'.format( disk.get('Size', ''), disk.get('Table', ''), disk.get('Type', ''), disk.get('Name', 'Unknown'), ) pwidth=len(str(len(disk['Partitions']))) for partition in disk['Partitions']: # Main text p_name = 'Partition {num:>{width}}: {size} ({fs})'.format( num = partition['Number'], width = pwidth, size = partition['Size'], fs = partition['FileSystem']) if partition['Name']: p_name += '\t"{}"'.format(partition['Name']) # Show unsupported partition(s) if is_bad_partition(partition): p_name = '{YELLOW}{p_name}{CLEAR}'.format( p_name=p_name, **COLORS) display_name += '\n\t\t\t{}'.format(p_name) if not disk['Partitions']: display_name += '\n\t\t\t{}No partitions found.{}'.format( COLORS['YELLOW'], COLORS['CLEAR']) disk_options.append({'Name': display_name, 'Disk': disk}) actions = [ {'Name': 'Main Menu', 'Letter': 'M'}, ] # Menu loop selection = menu_select( title = title, main_entries = disk_options, action_entries = actions) if (selection.isnumeric()): return disk_options[int(selection)-1]['Disk'] elif (selection == 'M'): raise GenericAbort if __name__ == '__main__': print("This file is not meant to be called directly.") # vim: sts=2 sw=2 ts=2
output = result.stdout.decode().strip() for tmp in re.findall(r'Disk (\d+)\s+\w+\s+(\d+\s+\w+)', output): num = tmp[0] size = human_readable_size(tmp[1]) disks.append({'Number': num, 'Size': size})
conditional_block
disk.py
# Wizard Kit: Functions - Disk from functions.common import * from settings.partition_uids import * # Regex REGEX_BAD_PARTITION = re.compile(r'(RAW|Unknown)', re.IGNORECASE) REGEX_DISK_GPT = re.compile( r'Disk ID: {[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+-[A-Z0-9]+}', re.IGNORECASE) REGEX_DISK_MBR = re.compile(r'Disk ID: [A-Z0-9]+', re.IGNORECASE) REGEX_DISK_RAW = re.compile(r'Disk ID: 00000000', re.IGNORECASE) def assign_volume_letters(): """Assign a volume letter to all available volumes.""" remove_volume_letters() # Write script script = [] for vol in get_volumes(): script.append('select volume {}'.format(vol['Number'])) script.append('assign') # Run run_diskpart(script) def get_boot_mode(): """Check if the boot mode was UEFI or legacy.""" boot_mode = 'Legacy' try: reg_key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control') reg_value = winreg.QueryValueEx(reg_key, 'PEFirmwareType')[0] if reg_value == 2: boot_mode = 'UEFI' except: boot_mode = 'Unknown' return boot_mode def get_disk_details(disk): """Get disk details using DiskPart.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'detail disk'] # Run try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Set disk name details['Name'] = tmp[4] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) return details def get_disks(): """Get list of attached disks using DiskPart.""" disks = [] try: # Run script result = run_diskpart(['list disk']) except subprocess.CalledProcessError: pass else: # Append disk numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Disk (\d+)\s+\w+\s+(\d+\s+\w+)', output): num = tmp[0] size = human_readable_size(tmp[1]) disks.append({'Number': num, 'Size': size}) return disks def get_partition_details(disk, partition): """Get partition details using DiskPart and fsutil.""" details = {} script = [ 'select disk {}'.format(disk['Number']), 'select partition {}'.format(partition['Number']), 'detail partition'] # Diskpart details try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Get volume letter or RAW status output = result.stdout.decode().strip() tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output) if tmp: if tmp.group(1).upper() == 'RAW': details['FileSystem'] = RAW else: details['Letter'] = tmp.group(1) # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Get MBR type / GPT GUID for extra details on "Unknown" partitions guid = PARTITION_UIDS.get(details.get('Type').upper(), {}) if guid: details.update({ 'Description': guid.get('Description', '')[:29], 'OS': guid.get('OS', 'Unknown')[:27]}) if 'Letter' in details: # Disk usage try: tmp = psutil.disk_usage('{}:\\'.format(details['Letter'])) except OSError as err: details['FileSystem'] = 'Unknown' details['Error'] = err.strerror else: details['Used Space'] = human_readable_size(tmp.used) # fsutil details cmd = [ 'fsutil', 'fsinfo', 'volumeinfo', '{}:'.format(details['Letter']) ] try: result = run_program(cmd) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() # Remove empty lines from output tmp = [s.strip() for s in output.splitlines() if s.strip() != ''] # Add "Feature" lines details['File System Features'] = [s.strip() for s in tmp if ':' not in s] # Split each line on ':' skipping those without ':' tmp = [s.split(':') for s in tmp if ':' in s] # Add key/value pairs to the details variable and return dict details.update({key.strip(): value.strip() for (key, value) in tmp}) # Set Volume Name details['Name'] = details.get('Volume Name', '') # Set FileSystem Type if details.get('FileSystem', '') not in ['RAW', 'Unknown']: details['FileSystem'] = details.get('File System Name', 'Unknown') return details def get_partitions(disk): """Get list of partition using DiskPart.""" partitions = [] script = [ 'select disk {}'.format(disk['Number']), 'list partition'] try: # Run script result = run_diskpart(script) except subprocess.CalledProcessError: pass else: # Append partition numbers output = result.stdout.decode().strip() regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+' for tmp in re.findall(regex, output, re.IGNORECASE): num = tmp[0] size = human_readable_size(tmp[1]) partitions.append({'Number': num, 'Size': size}) return partitions def get_table_type(disk): """Get disk partition table type using DiskPart.""" part_type = 'Unknown' script = [ 'select disk {}'.format(disk['Number']), 'uniqueid disk'] try: result = run_diskpart(script) except subprocess.CalledProcessError: pass else: output = result.stdout.decode().strip() if REGEX_DISK_GPT.search(output): part_type = 'GPT' elif REGEX_DISK_MBR.search(output): part_type = 'MBR' elif REGEX_DISK_RAW.search(output): part_type = 'RAW' return part_type def get_volumes(): """Get list of volumes using DiskPart.""" vols = [] try: result = run_diskpart(['list volume']) except subprocess.CalledProcessError: pass else: # Append volume numbers output = result.stdout.decode().strip() for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output): vols.append({'Number': tmp[0], 'Letter': tmp[1]}) return vols def is_bad_partition(par): """Check if the partition is accessible.""" return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem']) def prep_disk_for_formatting(disk=None): """Gather details about the disk and its partitions.""" disk['Format Warnings'] = '\n' width = len(str(len(disk['Partitions']))) # Bail early if disk is None: raise Exception('Disk not provided.') # Set boot method and partition table type disk['Use GPT'] = True if (get_boot_mode() == 'UEFI'): if (not ask("Setup Windows to use UEFI booting?")): disk['Use GPT'] = False else: if (ask("Setup Windows to use BIOS/Legacy booting?")): disk['Use GPT'] = False # Set Display and Warning Strings if len(disk['Partitions']) == 0: disk['Format Warnings'] += 'No partitions found\n' for partition in disk['Partitions']: display = '{size} {fs}'.format( num = partition['Number'], width = width, size = partition['Size'], fs = partition['FileSystem']) if is_bad_partition(partition): # Set display string using partition description & OS type display += '\t\t{q}{name}{q}\t{desc} ({os})'.format( display = display, q = '"' if partition['Name'] != '' else '', name = partition['Name'], desc = partition['Description'], os = partition['OS']) else: # List space used instead of partition description & OS type display += ' (Used: {used})\t{q}{name}{q}'.format( used = partition['Used Space'], q = '"' if partition['Name'] != '' else '', name = partition['Name']) # For all partitions partition['Display String'] = display def reassign_volume_letter(letter, new_letter='I'): """Assign a new letter to a volume using DiskPart.""" if not letter: # Ignore return None script = [ 'select volume {}'.format(letter), 'remove noerr', 'assign letter={}'.format(new_letter)] try: run_diskpart(script) except subprocess.CalledProcessError: pass else: return new_letter def remove_volume_letters(keep=None): """Remove all assigned volume letters using DiskPart.""" if not keep: keep = '' script = [] for vol in get_volumes(): if vol['Letter'].upper() != keep.upper(): script.append('select volume {}'.format(vol['Number'])) script.append('remove noerr') # Run script try: run_diskpart(script) except subprocess.CalledProcessError: pass def run_diskpart(script): """Run DiskPart script.""" tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP']) # Write script with open(tempfile, 'w') as f: for line in script: f.write('{}\n'.format(line)) # Run script cmd = [ r'{}\Windows\System32\diskpart.exe'.format( global_vars['Env']['SYSTEMDRIVE']), '/s', tempfile] result = run_program(cmd) sleep(2) return result def
(): """Get details about the attached disks""" disks = get_disks() # Get disk details for disk in disks: # Get partition style disk['Table'] = get_table_type(disk) # Get disk name/model and physical details disk.update(get_disk_details(disk)) # Get partition info for disk disk['Partitions'] = get_partitions(disk) for partition in disk['Partitions']: # Get partition details partition.update(get_partition_details(disk, partition)) # Done return disks def select_disk(title='Which disk?', disks=[]): """Select a disk from the attached disks""" # Build menu disk_options = [] for disk in disks: display_name = '{}\t[{}] ({}) {}'.format( disk.get('Size', ''), disk.get('Table', ''), disk.get('Type', ''), disk.get('Name', 'Unknown'), ) pwidth=len(str(len(disk['Partitions']))) for partition in disk['Partitions']: # Main text p_name = 'Partition {num:>{width}}: {size} ({fs})'.format( num = partition['Number'], width = pwidth, size = partition['Size'], fs = partition['FileSystem']) if partition['Name']: p_name += '\t"{}"'.format(partition['Name']) # Show unsupported partition(s) if is_bad_partition(partition): p_name = '{YELLOW}{p_name}{CLEAR}'.format( p_name=p_name, **COLORS) display_name += '\n\t\t\t{}'.format(p_name) if not disk['Partitions']: display_name += '\n\t\t\t{}No partitions found.{}'.format( COLORS['YELLOW'], COLORS['CLEAR']) disk_options.append({'Name': display_name, 'Disk': disk}) actions = [ {'Name': 'Main Menu', 'Letter': 'M'}, ] # Menu loop selection = menu_select( title = title, main_entries = disk_options, action_entries = actions) if (selection.isnumeric()): return disk_options[int(selection)-1]['Disk'] elif (selection == 'M'): raise GenericAbort if __name__ == '__main__': print("This file is not meant to be called directly.") # vim: sts=2 sw=2 ts=2
scan_disks
identifier_name
wiki.py
import os import re import random import hashlib import hmac from string import letters import logging import json import webapp2 import jinja2 import time from google.appengine.ext import db from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = False) jinja_env_escaped = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) #password hash using salt def make_salt(length = 5): return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(name, pw, salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) #cookie hashing and hash-validation functions secret = 'weneverwalkalone' def make_secure_cookie(val): return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_cookie(val): return val def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) #blog handler class BlogHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render_str_escaped(self, template, **params): t = jinja_env_escaped.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def render_content(self, template, **kw): content = self.render_str(template, **kw) self.render("index.html", content=content, user=self.get_logged_in_user(), **kw) def is_logged_in(self): user_id = None user = None user_id_str = self.request.cookies.get("user_id") if user_id_str: user_id = check_secure_val(user_id_str) return user_id def get_logged_in_user(self): user_id = self.is_logged_in() user = None if user_id: user = User.get_by_id(long(user_id)) return user #welcome handler class Welcome(BlogHandler): def get(self): cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name) if cookie_val: user_id = check_secure_val(str(cookie_val)) u = User.get_by_id(int(user_id)) self.render("welcome.html", username = u.username) else: self.redirect("/signup") # class for blog-post(subject and content) entries class Post(db.Model): subject = db.StringProperty(required = True) content = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n', '<br>') return render_str("post.html", p = self) # class for user entries class User(db.Model): username = db.StringProperty(required = True) password = db.StringProperty(required = True) email = db.StringProperty(required = False) # RegEx for the username field USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PASSWORD_RE = re.compile(r"^.{3,20}$") EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") # Validation for Usernames def valid_username(username): return USERNAME_RE.match(username) def valid_password(password): return PASSWORD_RE.match(password) def valid_email(email): return not email or EMAIL_RE.match(email) #handler for signup class Signup(BlogHandler): def get(self): self.render_content("signup.html") def post(self): have_error = False user_name = self.request.get('username') user_password = self.request.get('password') user_verify = self.request.get('verify') user_email = self.request.get('email') name_error = password_error = verify_error = email_error = "" if not valid_username(user_name): name_error = "That's not a valid username" have_error = True if not valid_password(user_password): password_error = "That's not a valid password" have_error = True elif user_password != user_verify: verify_error = "Your passwords didn't match" have_error = True if not valid_email(user_email): email_error = "That's not a valid email" have_error = True if have_error: self.render_content("signup.html" , username=user_name , username_error=name_error , password_error=password_error , verify_error=verify_error , email=user_email , email_error=email_error) else: u = User.gql("WHERE username = '%s'"%user_name).get() if u: name_error = "That user already exists." self.render_content("signup.html") else: # make salted password hash h = make_pw_hash(user_name, user_password) u = User(username=user_name, password=h,email=user_email) u.put() uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine) #The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect("/welcome") #login handler class Login(BlogHandler): def get(self): self.render_content("login-form.html") def post(self): user_name = self.request.get('username') user_password = self.request.get('password') u = User.gql("WHERE username = '%s'"%user_name).get() if u and valid_pw(user_name, user_password, u.password): uid= str(make_secure_cookie(str(u.key().id()))) self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect('/') else: msg = "Invalid login" self.render_content("login-form.html", error = msg) #logout handler class Logout(BlogHandler): def get(self): self.response.headers.add_header("Set-Cookie", "user_id=; Path=/") self.redirect("/signup") def top_posts(update = False): posts = memcache.get("top") if posts is None or update: posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) # to avoid querying in iterable memcache.set("top", posts) memcache.set("top_post_generated", time.time()) return posts #main page class MainPage(BlogHandler): def get(self): # posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") # caching for query above posts = top_posts() diff = time.time() - memcache.get("top_post_generated") self.render_content("front.html", posts=posts, time_update=str(int(diff))) def get_post(key): # cache function same as above but this one is for particular post post = memcache.get('post') if post and key == str(post.key().id()): return post else: post = Post.get_by_id(int(key)) memcache.set('post', post) memcache.set('post-generated', time.time()) return post # Handler for a specific Entry class SpecificPostHandler(BlogHandler): def get(self, key): post = get_post(key) diff = time.time() - memcache.get('post-generated') diff_str = "Queried %s seconds ago"%(str(int(diff))) self.render_content("permalink.html", post=post, time_update=diff_str) # Handler for posting newpoHandler for a specific Wiki Page Entrysts class EditPageHandler(BlogHandler): def get(self): if self.is_logged_in(): post = top_posts() self.render_content("newpost.html", post=post) else: self.redirect("/login") def post(self): if self.is_logged_in(): subject = self.request.get("subject") content = self.request.get("content") if subject and content: p = Post(subject=subject, content=content) p.put() KEY = p.key().id() top_posts(update = True) self.redirect("/"+str(KEY), str(KEY)) else: error = "subject and content, please!" self.render_content("newpost.html", subject=subject, content=content, error=error) else:
# /.json gives json of last 10 entries class JsonMainHandler(BlogHandler): def get(self): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) js = [] for p in posts:#json libraries in python excepts data types dat nos how 2 convert in json which're list,dict.. d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} js.append(d)#so created dictionary representation n later passed into json self.write(json.dumps(js))#json representation using dumps # /post-id.json gives json of that specific post class JsonSpecificPostHandler(BlogHandler): def get(self, key): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' p = Post.get_by_id(int(key)) d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} self.write(json.dumps(d)) class FlushHandler(BlogHandler): def get(self): memcache.flush_all() self.redirect('/') PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([('/', MainPage),('/edit', EditPageHandler), (r'/(\d+)', SpecificPostHandler),('/.json', JsonMainHandler), (r'/(\d+)'+".json",JsonSpecificPostHandler),('/signup', Signup), ('/login', Login),('/logout', Logout), ('/flush', FlushHandler), ('/welcome', Welcome)], debug=True)
self.redirect("/login")
conditional_block
wiki.py
import os import re import random import hashlib import hmac from string import letters import logging import json import webapp2 import jinja2 import time from google.appengine.ext import db from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = False) jinja_env_escaped = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) #password hash using salt def make_salt(length = 5): return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(name, pw, salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) #cookie hashing and hash-validation functions secret = 'weneverwalkalone' def make_secure_cookie(val): return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_cookie(val): return val def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) #blog handler class BlogHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render_str_escaped(self, template, **params): t = jinja_env_escaped.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def render_content(self, template, **kw): content = self.render_str(template, **kw) self.render("index.html", content=content, user=self.get_logged_in_user(), **kw) def is_logged_in(self): user_id = None user = None user_id_str = self.request.cookies.get("user_id") if user_id_str: user_id = check_secure_val(user_id_str) return user_id def get_logged_in_user(self): user_id = self.is_logged_in() user = None if user_id: user = User.get_by_id(long(user_id)) return user #welcome handler class Welcome(BlogHandler): def get(self): cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name) if cookie_val: user_id = check_secure_val(str(cookie_val)) u = User.get_by_id(int(user_id)) self.render("welcome.html", username = u.username) else: self.redirect("/signup") # class for blog-post(subject and content) entries class Post(db.Model): subject = db.StringProperty(required = True) content = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n', '<br>') return render_str("post.html", p = self) # class for user entries class User(db.Model): username = db.StringProperty(required = True) password = db.StringProperty(required = True) email = db.StringProperty(required = False) # RegEx for the username field USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PASSWORD_RE = re.compile(r"^.{3,20}$") EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") # Validation for Usernames def valid_username(username): return USERNAME_RE.match(username) def valid_password(password): return PASSWORD_RE.match(password) def valid_email(email): return not email or EMAIL_RE.match(email) #handler for signup class Signup(BlogHandler): def get(self): self.render_content("signup.html") def post(self): have_error = False user_name = self.request.get('username') user_password = self.request.get('password') user_verify = self.request.get('verify') user_email = self.request.get('email') name_error = password_error = verify_error = email_error = "" if not valid_username(user_name): name_error = "That's not a valid username" have_error = True if not valid_password(user_password): password_error = "That's not a valid password" have_error = True elif user_password != user_verify: verify_error = "Your passwords didn't match" have_error = True if not valid_email(user_email): email_error = "That's not a valid email" have_error = True if have_error: self.render_content("signup.html" , username=user_name , username_error=name_error , password_error=password_error , verify_error=verify_error , email=user_email , email_error=email_error) else: u = User.gql("WHERE username = '%s'"%user_name).get() if u: name_error = "That user already exists." self.render_content("signup.html") else: # make salted password hash h = make_pw_hash(user_name, user_password) u = User(username=user_name, password=h,email=user_email) u.put() uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine) #The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect("/welcome") #login handler class Login(BlogHandler): def
(self): self.render_content("login-form.html") def post(self): user_name = self.request.get('username') user_password = self.request.get('password') u = User.gql("WHERE username = '%s'"%user_name).get() if u and valid_pw(user_name, user_password, u.password): uid= str(make_secure_cookie(str(u.key().id()))) self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect('/') else: msg = "Invalid login" self.render_content("login-form.html", error = msg) #logout handler class Logout(BlogHandler): def get(self): self.response.headers.add_header("Set-Cookie", "user_id=; Path=/") self.redirect("/signup") def top_posts(update = False): posts = memcache.get("top") if posts is None or update: posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) # to avoid querying in iterable memcache.set("top", posts) memcache.set("top_post_generated", time.time()) return posts #main page class MainPage(BlogHandler): def get(self): # posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") # caching for query above posts = top_posts() diff = time.time() - memcache.get("top_post_generated") self.render_content("front.html", posts=posts, time_update=str(int(diff))) def get_post(key): # cache function same as above but this one is for particular post post = memcache.get('post') if post and key == str(post.key().id()): return post else: post = Post.get_by_id(int(key)) memcache.set('post', post) memcache.set('post-generated', time.time()) return post # Handler for a specific Entry class SpecificPostHandler(BlogHandler): def get(self, key): post = get_post(key) diff = time.time() - memcache.get('post-generated') diff_str = "Queried %s seconds ago"%(str(int(diff))) self.render_content("permalink.html", post=post, time_update=diff_str) # Handler for posting newpoHandler for a specific Wiki Page Entrysts class EditPageHandler(BlogHandler): def get(self): if self.is_logged_in(): post = top_posts() self.render_content("newpost.html", post=post) else: self.redirect("/login") def post(self): if self.is_logged_in(): subject = self.request.get("subject") content = self.request.get("content") if subject and content: p = Post(subject=subject, content=content) p.put() KEY = p.key().id() top_posts(update = True) self.redirect("/"+str(KEY), str(KEY)) else: error = "subject and content, please!" self.render_content("newpost.html", subject=subject, content=content, error=error) else: self.redirect("/login") # /.json gives json of last 10 entries class JsonMainHandler(BlogHandler): def get(self): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) js = [] for p in posts:#json libraries in python excepts data types dat nos how 2 convert in json which're list,dict.. d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} js.append(d)#so created dictionary representation n later passed into json self.write(json.dumps(js))#json representation using dumps # /post-id.json gives json of that specific post class JsonSpecificPostHandler(BlogHandler): def get(self, key): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' p = Post.get_by_id(int(key)) d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} self.write(json.dumps(d)) class FlushHandler(BlogHandler): def get(self): memcache.flush_all() self.redirect('/') PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([('/', MainPage),('/edit', EditPageHandler), (r'/(\d+)', SpecificPostHandler),('/.json', JsonMainHandler), (r'/(\d+)'+".json",JsonSpecificPostHandler),('/signup', Signup), ('/login', Login),('/logout', Logout), ('/flush', FlushHandler), ('/welcome', Welcome)], debug=True)
get
identifier_name
wiki.py
import os import re import random import hashlib import hmac from string import letters import logging import json import webapp2 import jinja2 import time from google.appengine.ext import db from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = False) jinja_env_escaped = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) #password hash using salt def make_salt(length = 5): return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(name, pw, salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) #cookie hashing and hash-validation functions secret = 'weneverwalkalone' def make_secure_cookie(val): return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_cookie(val): return val def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) #blog handler class BlogHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render_str_escaped(self, template, **params): t = jinja_env_escaped.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def render_content(self, template, **kw): content = self.render_str(template, **kw) self.render("index.html", content=content, user=self.get_logged_in_user(), **kw) def is_logged_in(self): user_id = None user = None user_id_str = self.request.cookies.get("user_id") if user_id_str: user_id = check_secure_val(user_id_str) return user_id def get_logged_in_user(self): user_id = self.is_logged_in() user = None if user_id: user = User.get_by_id(long(user_id)) return user #welcome handler class Welcome(BlogHandler): def get(self): cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name) if cookie_val: user_id = check_secure_val(str(cookie_val)) u = User.get_by_id(int(user_id)) self.render("welcome.html", username = u.username) else: self.redirect("/signup") # class for blog-post(subject and content) entries class Post(db.Model): subject = db.StringProperty(required = True) content = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n', '<br>') return render_str("post.html", p = self) # class for user entries class User(db.Model): username = db.StringProperty(required = True) password = db.StringProperty(required = True) email = db.StringProperty(required = False) # RegEx for the username field USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PASSWORD_RE = re.compile(r"^.{3,20}$") EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") # Validation for Usernames def valid_username(username): return USERNAME_RE.match(username) def valid_password(password): return PASSWORD_RE.match(password) def valid_email(email): return not email or EMAIL_RE.match(email) #handler for signup class Signup(BlogHandler): def get(self): self.render_content("signup.html") def post(self): have_error = False user_name = self.request.get('username') user_password = self.request.get('password') user_verify = self.request.get('verify') user_email = self.request.get('email') name_error = password_error = verify_error = email_error = "" if not valid_username(user_name): name_error = "That's not a valid username" have_error = True if not valid_password(user_password): password_error = "That's not a valid password" have_error = True elif user_password != user_verify: verify_error = "Your passwords didn't match" have_error = True
email_error = "That's not a valid email" have_error = True if have_error: self.render_content("signup.html" , username=user_name , username_error=name_error , password_error=password_error , verify_error=verify_error , email=user_email , email_error=email_error) else: u = User.gql("WHERE username = '%s'"%user_name).get() if u: name_error = "That user already exists." self.render_content("signup.html") else: # make salted password hash h = make_pw_hash(user_name, user_password) u = User(username=user_name, password=h,email=user_email) u.put() uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine) #The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect("/welcome") #login handler class Login(BlogHandler): def get(self): self.render_content("login-form.html") def post(self): user_name = self.request.get('username') user_password = self.request.get('password') u = User.gql("WHERE username = '%s'"%user_name).get() if u and valid_pw(user_name, user_password, u.password): uid= str(make_secure_cookie(str(u.key().id()))) self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect('/') else: msg = "Invalid login" self.render_content("login-form.html", error = msg) #logout handler class Logout(BlogHandler): def get(self): self.response.headers.add_header("Set-Cookie", "user_id=; Path=/") self.redirect("/signup") def top_posts(update = False): posts = memcache.get("top") if posts is None or update: posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) # to avoid querying in iterable memcache.set("top", posts) memcache.set("top_post_generated", time.time()) return posts #main page class MainPage(BlogHandler): def get(self): # posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") # caching for query above posts = top_posts() diff = time.time() - memcache.get("top_post_generated") self.render_content("front.html", posts=posts, time_update=str(int(diff))) def get_post(key): # cache function same as above but this one is for particular post post = memcache.get('post') if post and key == str(post.key().id()): return post else: post = Post.get_by_id(int(key)) memcache.set('post', post) memcache.set('post-generated', time.time()) return post # Handler for a specific Entry class SpecificPostHandler(BlogHandler): def get(self, key): post = get_post(key) diff = time.time() - memcache.get('post-generated') diff_str = "Queried %s seconds ago"%(str(int(diff))) self.render_content("permalink.html", post=post, time_update=diff_str) # Handler for posting newpoHandler for a specific Wiki Page Entrysts class EditPageHandler(BlogHandler): def get(self): if self.is_logged_in(): post = top_posts() self.render_content("newpost.html", post=post) else: self.redirect("/login") def post(self): if self.is_logged_in(): subject = self.request.get("subject") content = self.request.get("content") if subject and content: p = Post(subject=subject, content=content) p.put() KEY = p.key().id() top_posts(update = True) self.redirect("/"+str(KEY), str(KEY)) else: error = "subject and content, please!" self.render_content("newpost.html", subject=subject, content=content, error=error) else: self.redirect("/login") # /.json gives json of last 10 entries class JsonMainHandler(BlogHandler): def get(self): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) js = [] for p in posts:#json libraries in python excepts data types dat nos how 2 convert in json which're list,dict.. d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} js.append(d)#so created dictionary representation n later passed into json self.write(json.dumps(js))#json representation using dumps # /post-id.json gives json of that specific post class JsonSpecificPostHandler(BlogHandler): def get(self, key): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' p = Post.get_by_id(int(key)) d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} self.write(json.dumps(d)) class FlushHandler(BlogHandler): def get(self): memcache.flush_all() self.redirect('/') PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([('/', MainPage),('/edit', EditPageHandler), (r'/(\d+)', SpecificPostHandler),('/.json', JsonMainHandler), (r'/(\d+)'+".json",JsonSpecificPostHandler),('/signup', Signup), ('/login', Login),('/logout', Logout), ('/flush', FlushHandler), ('/welcome', Welcome)], debug=True)
if not valid_email(user_email):
random_line_split
wiki.py
import os import re import random import hashlib import hmac from string import letters import logging import json import webapp2 import jinja2 import time from google.appengine.ext import db from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = False) jinja_env_escaped = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) #password hash using salt def make_salt(length = 5): return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(name, pw, salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h) def valid_pw(name, password, h): salt = h.split(',')[0] return h == make_pw_hash(name, password, salt) #cookie hashing and hash-validation functions secret = 'weneverwalkalone' def make_secure_cookie(val): return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_cookie(val): return val def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) #blog handler class BlogHandler(webapp2.RequestHandler): def write(self, *a, **kw):
def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render_str_escaped(self, template, **params): t = jinja_env_escaped.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def render_content(self, template, **kw): content = self.render_str(template, **kw) self.render("index.html", content=content, user=self.get_logged_in_user(), **kw) def is_logged_in(self): user_id = None user = None user_id_str = self.request.cookies.get("user_id") if user_id_str: user_id = check_secure_val(user_id_str) return user_id def get_logged_in_user(self): user_id = self.is_logged_in() user = None if user_id: user = User.get_by_id(long(user_id)) return user #welcome handler class Welcome(BlogHandler): def get(self): cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name) if cookie_val: user_id = check_secure_val(str(cookie_val)) u = User.get_by_id(int(user_id)) self.render("welcome.html", username = u.username) else: self.redirect("/signup") # class for blog-post(subject and content) entries class Post(db.Model): subject = db.StringProperty(required = True) content = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n', '<br>') return render_str("post.html", p = self) # class for user entries class User(db.Model): username = db.StringProperty(required = True) password = db.StringProperty(required = True) email = db.StringProperty(required = False) # RegEx for the username field USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PASSWORD_RE = re.compile(r"^.{3,20}$") EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") # Validation for Usernames def valid_username(username): return USERNAME_RE.match(username) def valid_password(password): return PASSWORD_RE.match(password) def valid_email(email): return not email or EMAIL_RE.match(email) #handler for signup class Signup(BlogHandler): def get(self): self.render_content("signup.html") def post(self): have_error = False user_name = self.request.get('username') user_password = self.request.get('password') user_verify = self.request.get('verify') user_email = self.request.get('email') name_error = password_error = verify_error = email_error = "" if not valid_username(user_name): name_error = "That's not a valid username" have_error = True if not valid_password(user_password): password_error = "That's not a valid password" have_error = True elif user_password != user_verify: verify_error = "Your passwords didn't match" have_error = True if not valid_email(user_email): email_error = "That's not a valid email" have_error = True if have_error: self.render_content("signup.html" , username=user_name , username_error=name_error , password_error=password_error , verify_error=verify_error , email=user_email , email_error=email_error) else: u = User.gql("WHERE username = '%s'"%user_name).get() if u: name_error = "That user already exists." self.render_content("signup.html") else: # make salted password hash h = make_pw_hash(user_name, user_password) u = User(username=user_name, password=h,email=user_email) u.put() uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine) #The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect("/welcome") #login handler class Login(BlogHandler): def get(self): self.render_content("login-form.html") def post(self): user_name = self.request.get('username') user_password = self.request.get('password') u = User.gql("WHERE username = '%s'"%user_name).get() if u and valid_pw(user_name, user_password, u.password): uid= str(make_secure_cookie(str(u.key().id()))) self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid) self.redirect('/') else: msg = "Invalid login" self.render_content("login-form.html", error = msg) #logout handler class Logout(BlogHandler): def get(self): self.response.headers.add_header("Set-Cookie", "user_id=; Path=/") self.redirect("/signup") def top_posts(update = False): posts = memcache.get("top") if posts is None or update: posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) # to avoid querying in iterable memcache.set("top", posts) memcache.set("top_post_generated", time.time()) return posts #main page class MainPage(BlogHandler): def get(self): # posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") # caching for query above posts = top_posts() diff = time.time() - memcache.get("top_post_generated") self.render_content("front.html", posts=posts, time_update=str(int(diff))) def get_post(key): # cache function same as above but this one is for particular post post = memcache.get('post') if post and key == str(post.key().id()): return post else: post = Post.get_by_id(int(key)) memcache.set('post', post) memcache.set('post-generated', time.time()) return post # Handler for a specific Entry class SpecificPostHandler(BlogHandler): def get(self, key): post = get_post(key) diff = time.time() - memcache.get('post-generated') diff_str = "Queried %s seconds ago"%(str(int(diff))) self.render_content("permalink.html", post=post, time_update=diff_str) # Handler for posting newpoHandler for a specific Wiki Page Entrysts class EditPageHandler(BlogHandler): def get(self): if self.is_logged_in(): post = top_posts() self.render_content("newpost.html", post=post) else: self.redirect("/login") def post(self): if self.is_logged_in(): subject = self.request.get("subject") content = self.request.get("content") if subject and content: p = Post(subject=subject, content=content) p.put() KEY = p.key().id() top_posts(update = True) self.redirect("/"+str(KEY), str(KEY)) else: error = "subject and content, please!" self.render_content("newpost.html", subject=subject, content=content, error=error) else: self.redirect("/login") # /.json gives json of last 10 entries class JsonMainHandler(BlogHandler): def get(self): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10") posts = list(posts) js = [] for p in posts:#json libraries in python excepts data types dat nos how 2 convert in json which're list,dict.. d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} js.append(d)#so created dictionary representation n later passed into json self.write(json.dumps(js))#json representation using dumps # /post-id.json gives json of that specific post class JsonSpecificPostHandler(BlogHandler): def get(self, key): self.response.headers['Content-Type']= 'application/json; charset=UTF-8' p = Post.get_by_id(int(key)) d = {'content': p.content, 'subject': p.subject, 'created': (p.created.strftime('%c')), 'last_modified': (p.created.strftime('%c'))} self.write(json.dumps(d)) class FlushHandler(BlogHandler): def get(self): memcache.flush_all() self.redirect('/') PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)' app = webapp2.WSGIApplication([('/', MainPage),('/edit', EditPageHandler), (r'/(\d+)', SpecificPostHandler),('/.json', JsonMainHandler), (r'/(\d+)'+".json",JsonSpecificPostHandler),('/signup', Signup), ('/login', Login),('/logout', Logout), ('/flush', FlushHandler), ('/welcome', Welcome)], debug=True)
self.response.out.write(*a, **kw)
identifier_body
keyvault.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: keyvault.proto package security import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" common "github.com/microsoft/moc/rpc/common" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type KeyVaultRequest struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` OperationType common.Operation `protobuf:"varint,2,opt,name=OperationType,proto3,enum=moc.Operation" json:"OperationType,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultRequest) Reset() { *m = KeyVaultRequest{} } func (m *KeyVaultRequest) String() string { return proto.CompactTextString(m) } func (*KeyVaultRequest) ProtoMessage() {} func (*KeyVaultRequest) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{0} } func (m *KeyVaultRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultRequest.Unmarshal(m, b) } func (m *KeyVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultRequest.Marshal(b, m, deterministic) } func (m *KeyVaultRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultRequest.Merge(m, src) } func (m *KeyVaultRequest) XXX_Size() int { return xxx_messageInfo_KeyVaultRequest.Size(m) } func (m *KeyVaultRequest) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultRequest.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultRequest proto.InternalMessageInfo func (m *KeyVaultRequest) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultRequest) GetOperationType() common.Operation { if m != nil { return m.OperationType } return common.Operation_GET } type KeyVaultResponse struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"` Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultResponse) Reset() { *m = KeyVaultResponse{} } func (m *KeyVaultResponse) String() string { return proto.CompactTextString(m) } func (*KeyVaultResponse) ProtoMessage() {} func (*KeyVaultResponse) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{1} } func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b) } func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic) } func (m *KeyVaultResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultResponse.Merge(m, src) } func (m *KeyVaultResponse) XXX_Size() int { return xxx_messageInfo_KeyVaultResponse.Size(m) } func (m *KeyVaultResponse) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue { if m != nil { return m.Result } return nil } func (m *KeyVaultResponse) GetError() string { if m != nil { return m.Error } return "" } type KeyVault struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"` GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"` Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVault) Reset()
func (m *KeyVault) String() string { return proto.CompactTextString(m) } func (*KeyVault) ProtoMessage() {} func (*KeyVault) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{2} } func (m *KeyVault) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVault.Unmarshal(m, b) } func (m *KeyVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic) } func (m *KeyVault) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVault.Merge(m, src) } func (m *KeyVault) XXX_Size() int { return xxx_messageInfo_KeyVault.Size(m) } func (m *KeyVault) XXX_DiscardUnknown() { xxx_messageInfo_KeyVault.DiscardUnknown(m) } var xxx_messageInfo_KeyVault proto.InternalMessageInfo func (m *KeyVault) GetName() string { if m != nil { return m.Name } return "" } func (m *KeyVault) GetId() string { if m != nil { return m.Id } return "" } func (m *KeyVault) GetSecrets() []*Secret { if m != nil { return m.Secrets } return nil } func (m *KeyVault) GetGroupName() string { if m != nil { return m.GroupName } return "" } func (m *KeyVault) GetStatus() *common.Status { if m != nil { return m.Status } return nil } func (m *KeyVault) GetLocationName() string { if m != nil { return m.LocationName } return "" } func init() { proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest") proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse") proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault") } func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) } var fileDescriptor_4c3d44d2a4b8394c = []byte{ // 411 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40, 0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98, 0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8, 0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48, 0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18, 0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 0xa4, 0xa5, 0xae, 0x29, 0x6c, 0x8b, 0x12, 0x5b, 0x2f, 0x1d, 0xea, 0x60, 0x2b, 0xdf, 0xad, 0x9e, 0x94, 0x44, 0x65, 0x8d, 0x19, 0xcb, 0x36, 0xe1, 0x3c, 0xfb, 0x69, 0x0b, 0x63, 0xd0, 0xba, 0xbe, 0x71, 0x75, 0xa4, 0xa9, 0x69, 0xa8, 0x1d, 0x4e, 0x0e, 0xb5, 0xc5, 0x3d, 0x34, 0xf9, 0x15, 0xc1, 0xfd, 0x8f, 0xd8, 0x9d, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a, 0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3, 0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, 0xd2, 0x65, 0xbe, 0x64, 0xc8, 0xd5, 0x8d, 0xba, 0x2e, 0x4a, 0x7e, 0x47, 0xf0, 0x60, 0xb4, 0xe2, 0x0c, 0xb5, 0x0e, 0x6f, 0xef, 0x25, 0x87, 0x99, 0x42, 0x17, 0x6a, 0xcf, 0x26, 0x16, 0xf9, 0x4a, 0xf6, 0x69, 0xc9, 0x21, 0x2d, 0x79, 0x42, 0x54, 0x9f, 0x15, 0x75, 0x40, 0xb5, 0x57, 0x8a, 0x87, 0x70, 0xf8, 0xde, 0x5a, 0xb2, 0xf1, 0x74, 0x1d, 0xa5, 0x73, 0xd5, 0x1f, 0x92, 0x3f, 0x11, 0xdc, 0x1b, 0xb8, 0x42, 0xc0, 0x41, 0x5b, 0x34, 0x18, 0x47, 0xac, 0xe0, 0x6f, 0xb1, 0x84, 0x49, 0xb5, 0xe5, 0x31, 0x73, 0x35, 0xa9, 0xb6, 0xe2, 0x0d, 0xdc, 0x3d, 0xe5, 0xac, 0x5d, 0x3c, 0x65, 0xe7, 0x4f, 0x6f, 0x74, 0xde, 0xeb, 0xd4, 0xa0, 0x17, 0x8f, 0x61, 0x5e, 0x5a, 0x0a, 0xe6, 0xd3, 0x6e, 0xc6, 0x01, 0x13, 0xc7, 0x82, 0x78, 0x0e, 0x33, 0xe7, 0x0b, 0x1f, 0x5c, 0x7c, 0xc8, 0x6f, 0x5a, 0x30, 0xf7, 0x94, 0x4b, 0x6a, 0x7f, 0x25, 0x12, 0x38, 0xaa, 0x49, 0x73, 0xbc, 0x4c, 0x01, 0xa6, 0x5c, 0xab, 0xe5, 0x06, 0x8e, 0x87, 0x17, 0xbd, 0xdb, 0x19, 0x12, 0xdf, 0x60, 0xf6, 0xa1, 0xbd, 0xa4, 0x0b, 0x14, 0xe9, 0xbf, 0x53, 0xee, 0x7f, 0x97, 0xd5, 0x8b, 0xff, 0x50, 0xf6, 0xdb, 0x4c, 0xee, 0x9c, 0xe4, 0x5f, 0x5f, 0x96, 0x95, 0xff, 0x1e, 0x36, 0x52, 0x53, 0x93, 0x35, 0x95, 0xb6, 0xe4, 0xe8, 0xdc, 0x67, 0x0d, 0xe9, 0xcc, 0x1a, 0x9d, 0x8d, 0x98, 0x6c, 0xc0, 0x6c, 0x66, 0xbc, 0xaa, 0x57, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x2b, 0x2e, 0xad, 0x5d, 0x11, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // KeyVaultAgentClient is the client API for KeyVaultAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type KeyVaultAgentClient interface { Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) } type keyVaultAgentClient struct { cc *grpc.ClientConn } func NewKeyVaultAgentClient(cc *grpc.ClientConn) KeyVaultAgentClient { return &keyVaultAgentClient{cc} } func (c *keyVaultAgentClient) Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) { out := new(KeyVaultResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.security.KeyVaultAgent/Invoke", in, out, opts...) if err != nil { return nil, err } return out, nil } // KeyVaultAgentServer is the server API for KeyVaultAgent service. type KeyVaultAgentServer interface { Invoke(context.Context, *KeyVaultRequest) (*KeyVaultResponse, error) } // UnimplementedKeyVaultAgentServer can be embedded to have forward compatible implementations. type UnimplementedKeyVaultAgentServer struct { } func (*UnimplementedKeyVaultAgentServer) Invoke(ctx context.Context, req *KeyVaultRequest) (*KeyVaultResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Invoke not implemented") } func RegisterKeyVaultAgentServer(s *grpc.Server, srv KeyVaultAgentServer) { s.RegisterService(&_KeyVaultAgent_serviceDesc, srv) } func _KeyVaultAgent_Invoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KeyVaultRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(KeyVaultAgentServer).Invoke(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.security.KeyVaultAgent/Invoke", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(KeyVaultAgentServer).Invoke(ctx, req.(*KeyVaultRequest)) } return interceptor(ctx, in, info, handler) } var _KeyVaultAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "moc.cloudagent.security.KeyVaultAgent", HandlerType: (*KeyVaultAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Invoke", Handler: _KeyVaultAgent_Invoke_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "keyvault.proto", }
{ *m = KeyVault{} }
identifier_body
keyvault.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: keyvault.proto package security import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" common "github.com/microsoft/moc/rpc/common" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type KeyVaultRequest struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` OperationType common.Operation `protobuf:"varint,2,opt,name=OperationType,proto3,enum=moc.Operation" json:"OperationType,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultRequest) Reset() { *m = KeyVaultRequest{} } func (m *KeyVaultRequest) String() string { return proto.CompactTextString(m) } func (*KeyVaultRequest) ProtoMessage() {} func (*KeyVaultRequest) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{0} } func (m *KeyVaultRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultRequest.Unmarshal(m, b) } func (m *KeyVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultRequest.Marshal(b, m, deterministic) } func (m *KeyVaultRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultRequest.Merge(m, src) } func (m *KeyVaultRequest) XXX_Size() int { return xxx_messageInfo_KeyVaultRequest.Size(m) } func (m *KeyVaultRequest) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultRequest.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultRequest proto.InternalMessageInfo func (m *KeyVaultRequest) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultRequest) GetOperationType() common.Operation { if m != nil { return m.OperationType } return common.Operation_GET } type KeyVaultResponse struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"` Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultResponse) Reset() { *m = KeyVaultResponse{} } func (m *KeyVaultResponse) String() string { return proto.CompactTextString(m) } func (*KeyVaultResponse) ProtoMessage() {} func (*KeyVaultResponse) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{1} } func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b) } func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic) } func (m *KeyVaultResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultResponse.Merge(m, src) } func (m *KeyVaultResponse) XXX_Size() int { return xxx_messageInfo_KeyVaultResponse.Size(m) } func (m *KeyVaultResponse) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue { if m != nil { return m.Result } return nil } func (m *KeyVaultResponse) GetError() string { if m != nil { return m.Error } return "" } type KeyVault struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"` GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"` Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVault) Reset() { *m = KeyVault{} } func (m *KeyVault) String() string { return proto.CompactTextString(m) } func (*KeyVault) ProtoMessage() {} func (*KeyVault) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{2} } func (m *KeyVault) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVault.Unmarshal(m, b) } func (m *KeyVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic) } func (m *KeyVault) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVault.Merge(m, src) } func (m *KeyVault) XXX_Size() int { return xxx_messageInfo_KeyVault.Size(m) } func (m *KeyVault) XXX_DiscardUnknown() { xxx_messageInfo_KeyVault.DiscardUnknown(m) } var xxx_messageInfo_KeyVault proto.InternalMessageInfo func (m *KeyVault) GetName() string { if m != nil { return m.Name } return "" } func (m *KeyVault) GetId() string { if m != nil { return m.Id } return "" } func (m *KeyVault) GetSecrets() []*Secret { if m != nil { return m.Secrets } return nil } func (m *KeyVault) GetGroupName() string { if m != nil { return m.GroupName } return "" } func (m *KeyVault) GetStatus() *common.Status { if m != nil { return m.Status } return nil } func (m *KeyVault) GetLocationName() string { if m != nil { return m.LocationName } return "" } func init() { proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest") proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse") proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault") } func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) } var fileDescriptor_4c3d44d2a4b8394c = []byte{ // 411 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40, 0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98, 0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8, 0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48, 0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18, 0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 0xa4, 0xa5, 0xae, 0x29, 0x6c, 0x8b, 0x12, 0x5b, 0x2f, 0x1d, 0xea, 0x60, 0x2b, 0xdf, 0xad, 0x9e, 0x94, 0x44, 0x65, 0x8d, 0x19, 0xcb, 0x36, 0xe1, 0x3c, 0xfb, 0x69, 0x0b, 0x63, 0xd0, 0xba, 0xbe, 0x71, 0x75, 0xa4, 0xa9, 0x69, 0xa8, 0x1d, 0x4e, 0x0e, 0xb5, 0xc5, 0x3d, 0x34, 0xf9, 0x15, 0xc1, 0xfd, 0x8f, 0xd8, 0x9d, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a, 0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3, 0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, 0xd2, 0x65, 0xbe, 0x64, 0xc8, 0xd5, 0x8d, 0xba, 0x2e, 0x4a, 0x7e, 0x47, 0xf0, 0x60, 0xb4, 0xe2, 0x0c, 0xb5, 0x0e, 0x6f, 0xef, 0x25, 0x87, 0x99, 0x42, 0x17, 0x6a, 0xcf, 0x26, 0x16, 0xf9, 0x4a, 0xf6, 0x69, 0xc9, 0x21, 0x2d, 0x79, 0x42, 0x54, 0x9f, 0x15, 0x75, 0x40, 0xb5, 0x57, 0x8a, 0x87, 0x70, 0xf8, 0xde, 0x5a, 0xb2, 0xf1, 0x74, 0x1d, 0xa5, 0x73, 0xd5, 0x1f, 0x92, 0x3f, 0x11, 0xdc, 0x1b, 0xb8, 0x42, 0xc0, 0x41, 0x5b, 0x34, 0x18, 0x47, 0xac, 0xe0, 0x6f, 0xb1, 0x84, 0x49, 0xb5, 0xe5, 0x31, 0x73, 0x35, 0xa9, 0xb6, 0xe2, 0x0d, 0xdc, 0x3d, 0xe5, 0xac, 0x5d, 0x3c, 0x65, 0xe7, 0x4f, 0x6f, 0x74, 0xde, 0xeb, 0xd4, 0xa0, 0x17, 0x8f, 0x61, 0x5e, 0x5a, 0x0a, 0xe6, 0xd3, 0x6e, 0xc6, 0x01, 0x13, 0xc7, 0x82, 0x78, 0x0e, 0x33, 0xe7, 0x0b, 0x1f, 0x5c, 0x7c, 0xc8, 0x6f, 0x5a, 0x30, 0xf7, 0x94, 0x4b, 0x6a, 0x7f, 0x25, 0x12, 0x38, 0xaa, 0x49, 0x73, 0xbc, 0x4c, 0x01, 0xa6, 0x5c, 0xab, 0xe5, 0x06, 0x8e, 0x87, 0x17, 0xbd, 0xdb, 0x19, 0x12, 0xdf, 0x60, 0xf6, 0xa1, 0xbd, 0xa4, 0x0b, 0x14, 0xe9, 0xbf, 0x53, 0xee, 0x7f, 0x97, 0xd5, 0x8b, 0xff, 0x50, 0xf6, 0xdb, 0x4c, 0xee, 0x9c, 0xe4, 0x5f, 0x5f, 0x96, 0x95, 0xff, 0x1e, 0x36, 0x52, 0x53, 0x93, 0x35, 0x95, 0xb6, 0xe4, 0xe8, 0xdc, 0x67, 0x0d, 0xe9, 0xcc, 0x1a, 0x9d, 0x8d, 0x98, 0x6c, 0xc0, 0x6c, 0x66, 0xbc, 0xaa, 0x57, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x2b, 0x2e, 0xad, 0x5d, 0x11, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // KeyVaultAgentClient is the client API for KeyVaultAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type KeyVaultAgentClient interface { Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) } type keyVaultAgentClient struct { cc *grpc.ClientConn } func NewKeyVaultAgentClient(cc *grpc.ClientConn) KeyVaultAgentClient { return &keyVaultAgentClient{cc} } func (c *keyVaultAgentClient) Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) { out := new(KeyVaultResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.security.KeyVaultAgent/Invoke", in, out, opts...) if err != nil { return nil, err } return out, nil } // KeyVaultAgentServer is the server API for KeyVaultAgent service. type KeyVaultAgentServer interface {
// UnimplementedKeyVaultAgentServer can be embedded to have forward compatible implementations. type UnimplementedKeyVaultAgentServer struct { } func (*UnimplementedKeyVaultAgentServer) Invoke(ctx context.Context, req *KeyVaultRequest) (*KeyVaultResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Invoke not implemented") } func RegisterKeyVaultAgentServer(s *grpc.Server, srv KeyVaultAgentServer) { s.RegisterService(&_KeyVaultAgent_serviceDesc, srv) } func _KeyVaultAgent_Invoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KeyVaultRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(KeyVaultAgentServer).Invoke(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.security.KeyVaultAgent/Invoke", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(KeyVaultAgentServer).Invoke(ctx, req.(*KeyVaultRequest)) } return interceptor(ctx, in, info, handler) } var _KeyVaultAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "moc.cloudagent.security.KeyVaultAgent", HandlerType: (*KeyVaultAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Invoke", Handler: _KeyVaultAgent_Invoke_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "keyvault.proto", }
Invoke(context.Context, *KeyVaultRequest) (*KeyVaultResponse, error) }
random_line_split
keyvault.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: keyvault.proto package security import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" common "github.com/microsoft/moc/rpc/common" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type KeyVaultRequest struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` OperationType common.Operation `protobuf:"varint,2,opt,name=OperationType,proto3,enum=moc.Operation" json:"OperationType,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultRequest) Reset() { *m = KeyVaultRequest{} } func (m *KeyVaultRequest) String() string { return proto.CompactTextString(m) } func (*KeyVaultRequest) ProtoMessage() {} func (*KeyVaultRequest) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{0} } func (m *KeyVaultRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultRequest.Unmarshal(m, b) } func (m *KeyVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultRequest.Marshal(b, m, deterministic) } func (m *KeyVaultRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultRequest.Merge(m, src) } func (m *KeyVaultRequest) XXX_Size() int { return xxx_messageInfo_KeyVaultRequest.Size(m) } func (m *KeyVaultRequest) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultRequest.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultRequest proto.InternalMessageInfo func (m *KeyVaultRequest) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultRequest) GetOperationType() common.Operation { if m != nil { return m.OperationType } return common.Operation_GET } type KeyVaultResponse struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"` Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultResponse) Reset() { *m = KeyVaultResponse{} } func (m *KeyVaultResponse) String() string { return proto.CompactTextString(m) } func (*KeyVaultResponse) ProtoMessage() {} func (*KeyVaultResponse) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{1} } func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b) } func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic) } func (m *KeyVaultResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultResponse.Merge(m, src) } func (m *KeyVaultResponse) XXX_Size() int { return xxx_messageInfo_KeyVaultResponse.Size(m) } func (m *KeyVaultResponse) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue { if m != nil { return m.Result } return nil } func (m *KeyVaultResponse) GetError() string { if m != nil { return m.Error } return "" } type KeyVault struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"` GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"` Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVault) Reset() { *m = KeyVault{} } func (m *KeyVault) String() string { return proto.CompactTextString(m) } func (*KeyVault) ProtoMessage() {} func (*KeyVault) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{2} } func (m *KeyVault) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVault.Unmarshal(m, b) } func (m *KeyVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic) } func (m *KeyVault) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVault.Merge(m, src) } func (m *KeyVault) XXX_Size() int { return xxx_messageInfo_KeyVault.Size(m) } func (m *KeyVault) XXX_DiscardUnknown() { xxx_messageInfo_KeyVault.DiscardUnknown(m) } var xxx_messageInfo_KeyVault proto.InternalMessageInfo func (m *KeyVault) GetName() string { if m != nil
return "" } func (m *KeyVault) GetId() string { if m != nil { return m.Id } return "" } func (m *KeyVault) GetSecrets() []*Secret { if m != nil { return m.Secrets } return nil } func (m *KeyVault) GetGroupName() string { if m != nil { return m.GroupName } return "" } func (m *KeyVault) GetStatus() *common.Status { if m != nil { return m.Status } return nil } func (m *KeyVault) GetLocationName() string { if m != nil { return m.LocationName } return "" } func init() { proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest") proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse") proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault") } func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) } var fileDescriptor_4c3d44d2a4b8394c = []byte{ // 411 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40, 0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98, 0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8, 0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48, 0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18, 0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 0xa4, 0xa5, 0xae, 0x29, 0x6c, 0x8b, 0x12, 0x5b, 0x2f, 0x1d, 0xea, 0x60, 0x2b, 0xdf, 0xad, 0x9e, 0x94, 0x44, 0x65, 0x8d, 0x19, 0xcb, 0x36, 0xe1, 0x3c, 0xfb, 0x69, 0x0b, 0x63, 0xd0, 0xba, 0xbe, 0x71, 0x75, 0xa4, 0xa9, 0x69, 0xa8, 0x1d, 0x4e, 0x0e, 0xb5, 0xc5, 0x3d, 0x34, 0xf9, 0x15, 0xc1, 0xfd, 0x8f, 0xd8, 0x9d, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a, 0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3, 0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, 0xd2, 0x65, 0xbe, 0x64, 0xc8, 0xd5, 0x8d, 0xba, 0x2e, 0x4a, 0x7e, 0x47, 0xf0, 0x60, 0xb4, 0xe2, 0x0c, 0xb5, 0x0e, 0x6f, 0xef, 0x25, 0x87, 0x99, 0x42, 0x17, 0x6a, 0xcf, 0x26, 0x16, 0xf9, 0x4a, 0xf6, 0x69, 0xc9, 0x21, 0x2d, 0x79, 0x42, 0x54, 0x9f, 0x15, 0x75, 0x40, 0xb5, 0x57, 0x8a, 0x87, 0x70, 0xf8, 0xde, 0x5a, 0xb2, 0xf1, 0x74, 0x1d, 0xa5, 0x73, 0xd5, 0x1f, 0x92, 0x3f, 0x11, 0xdc, 0x1b, 0xb8, 0x42, 0xc0, 0x41, 0x5b, 0x34, 0x18, 0x47, 0xac, 0xe0, 0x6f, 0xb1, 0x84, 0x49, 0xb5, 0xe5, 0x31, 0x73, 0x35, 0xa9, 0xb6, 0xe2, 0x0d, 0xdc, 0x3d, 0xe5, 0xac, 0x5d, 0x3c, 0x65, 0xe7, 0x4f, 0x6f, 0x74, 0xde, 0xeb, 0xd4, 0xa0, 0x17, 0x8f, 0x61, 0x5e, 0x5a, 0x0a, 0xe6, 0xd3, 0x6e, 0xc6, 0x01, 0x13, 0xc7, 0x82, 0x78, 0x0e, 0x33, 0xe7, 0x0b, 0x1f, 0x5c, 0x7c, 0xc8, 0x6f, 0x5a, 0x30, 0xf7, 0x94, 0x4b, 0x6a, 0x7f, 0x25, 0x12, 0x38, 0xaa, 0x49, 0x73, 0xbc, 0x4c, 0x01, 0xa6, 0x5c, 0xab, 0xe5, 0x06, 0x8e, 0x87, 0x17, 0xbd, 0xdb, 0x19, 0x12, 0xdf, 0x60, 0xf6, 0xa1, 0xbd, 0xa4, 0x0b, 0x14, 0xe9, 0xbf, 0x53, 0xee, 0x7f, 0x97, 0xd5, 0x8b, 0xff, 0x50, 0xf6, 0xdb, 0x4c, 0xee, 0x9c, 0xe4, 0x5f, 0x5f, 0x96, 0x95, 0xff, 0x1e, 0x36, 0x52, 0x53, 0x93, 0x35, 0x95, 0xb6, 0xe4, 0xe8, 0xdc, 0x67, 0x0d, 0xe9, 0xcc, 0x1a, 0x9d, 0x8d, 0x98, 0x6c, 0xc0, 0x6c, 0x66, 0xbc, 0xaa, 0x57, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x2b, 0x2e, 0xad, 0x5d, 0x11, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // KeyVaultAgentClient is the client API for KeyVaultAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type KeyVaultAgentClient interface { Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) } type keyVaultAgentClient struct { cc *grpc.ClientConn } func NewKeyVaultAgentClient(cc *grpc.ClientConn) KeyVaultAgentClient { return &keyVaultAgentClient{cc} } func (c *keyVaultAgentClient) Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) { out := new(KeyVaultResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.security.KeyVaultAgent/Invoke", in, out, opts...) if err != nil { return nil, err } return out, nil } // KeyVaultAgentServer is the server API for KeyVaultAgent service. type KeyVaultAgentServer interface { Invoke(context.Context, *KeyVaultRequest) (*KeyVaultResponse, error) } // UnimplementedKeyVaultAgentServer can be embedded to have forward compatible implementations. type UnimplementedKeyVaultAgentServer struct { } func (*UnimplementedKeyVaultAgentServer) Invoke(ctx context.Context, req *KeyVaultRequest) (*KeyVaultResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Invoke not implemented") } func RegisterKeyVaultAgentServer(s *grpc.Server, srv KeyVaultAgentServer) { s.RegisterService(&_KeyVaultAgent_serviceDesc, srv) } func _KeyVaultAgent_Invoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KeyVaultRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(KeyVaultAgentServer).Invoke(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.security.KeyVaultAgent/Invoke", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(KeyVaultAgentServer).Invoke(ctx, req.(*KeyVaultRequest)) } return interceptor(ctx, in, info, handler) } var _KeyVaultAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "moc.cloudagent.security.KeyVaultAgent", HandlerType: (*KeyVaultAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Invoke", Handler: _KeyVaultAgent_Invoke_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "keyvault.proto", }
{ return m.Name }
conditional_block
keyvault.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: keyvault.proto package security import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" common "github.com/microsoft/moc/rpc/common" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type KeyVaultRequest struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` OperationType common.Operation `protobuf:"varint,2,opt,name=OperationType,proto3,enum=moc.Operation" json:"OperationType,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultRequest)
() { *m = KeyVaultRequest{} } func (m *KeyVaultRequest) String() string { return proto.CompactTextString(m) } func (*KeyVaultRequest) ProtoMessage() {} func (*KeyVaultRequest) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{0} } func (m *KeyVaultRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultRequest.Unmarshal(m, b) } func (m *KeyVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultRequest.Marshal(b, m, deterministic) } func (m *KeyVaultRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultRequest.Merge(m, src) } func (m *KeyVaultRequest) XXX_Size() int { return xxx_messageInfo_KeyVaultRequest.Size(m) } func (m *KeyVaultRequest) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultRequest.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultRequest proto.InternalMessageInfo func (m *KeyVaultRequest) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultRequest) GetOperationType() common.Operation { if m != nil { return m.OperationType } return common.Operation_GET } type KeyVaultResponse struct { KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"` Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"` Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVaultResponse) Reset() { *m = KeyVaultResponse{} } func (m *KeyVaultResponse) String() string { return proto.CompactTextString(m) } func (*KeyVaultResponse) ProtoMessage() {} func (*KeyVaultResponse) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{1} } func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b) } func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic) } func (m *KeyVaultResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVaultResponse.Merge(m, src) } func (m *KeyVaultResponse) XXX_Size() int { return xxx_messageInfo_KeyVaultResponse.Size(m) } func (m *KeyVaultResponse) XXX_DiscardUnknown() { xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m) } var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault { if m != nil { return m.KeyVaults } return nil } func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue { if m != nil { return m.Result } return nil } func (m *KeyVaultResponse) GetError() string { if m != nil { return m.Error } return "" } type KeyVault struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"` GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"` Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeyVault) Reset() { *m = KeyVault{} } func (m *KeyVault) String() string { return proto.CompactTextString(m) } func (*KeyVault) ProtoMessage() {} func (*KeyVault) Descriptor() ([]byte, []int) { return fileDescriptor_4c3d44d2a4b8394c, []int{2} } func (m *KeyVault) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeyVault.Unmarshal(m, b) } func (m *KeyVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic) } func (m *KeyVault) XXX_Merge(src proto.Message) { xxx_messageInfo_KeyVault.Merge(m, src) } func (m *KeyVault) XXX_Size() int { return xxx_messageInfo_KeyVault.Size(m) } func (m *KeyVault) XXX_DiscardUnknown() { xxx_messageInfo_KeyVault.DiscardUnknown(m) } var xxx_messageInfo_KeyVault proto.InternalMessageInfo func (m *KeyVault) GetName() string { if m != nil { return m.Name } return "" } func (m *KeyVault) GetId() string { if m != nil { return m.Id } return "" } func (m *KeyVault) GetSecrets() []*Secret { if m != nil { return m.Secrets } return nil } func (m *KeyVault) GetGroupName() string { if m != nil { return m.GroupName } return "" } func (m *KeyVault) GetStatus() *common.Status { if m != nil { return m.Status } return nil } func (m *KeyVault) GetLocationName() string { if m != nil { return m.LocationName } return "" } func init() { proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest") proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse") proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault") } func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) } var fileDescriptor_4c3d44d2a4b8394c = []byte{ // 411 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40, 0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98, 0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8, 0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48, 0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18, 0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 0xa4, 0xa5, 0xae, 0x29, 0x6c, 0x8b, 0x12, 0x5b, 0x2f, 0x1d, 0xea, 0x60, 0x2b, 0xdf, 0xad, 0x9e, 0x94, 0x44, 0x65, 0x8d, 0x19, 0xcb, 0x36, 0xe1, 0x3c, 0xfb, 0x69, 0x0b, 0x63, 0xd0, 0xba, 0xbe, 0x71, 0x75, 0xa4, 0xa9, 0x69, 0xa8, 0x1d, 0x4e, 0x0e, 0xb5, 0xc5, 0x3d, 0x34, 0xf9, 0x15, 0xc1, 0xfd, 0x8f, 0xd8, 0x9d, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a, 0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3, 0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, 0xd2, 0x65, 0xbe, 0x64, 0xc8, 0xd5, 0x8d, 0xba, 0x2e, 0x4a, 0x7e, 0x47, 0xf0, 0x60, 0xb4, 0xe2, 0x0c, 0xb5, 0x0e, 0x6f, 0xef, 0x25, 0x87, 0x99, 0x42, 0x17, 0x6a, 0xcf, 0x26, 0x16, 0xf9, 0x4a, 0xf6, 0x69, 0xc9, 0x21, 0x2d, 0x79, 0x42, 0x54, 0x9f, 0x15, 0x75, 0x40, 0xb5, 0x57, 0x8a, 0x87, 0x70, 0xf8, 0xde, 0x5a, 0xb2, 0xf1, 0x74, 0x1d, 0xa5, 0x73, 0xd5, 0x1f, 0x92, 0x3f, 0x11, 0xdc, 0x1b, 0xb8, 0x42, 0xc0, 0x41, 0x5b, 0x34, 0x18, 0x47, 0xac, 0xe0, 0x6f, 0xb1, 0x84, 0x49, 0xb5, 0xe5, 0x31, 0x73, 0x35, 0xa9, 0xb6, 0xe2, 0x0d, 0xdc, 0x3d, 0xe5, 0xac, 0x5d, 0x3c, 0x65, 0xe7, 0x4f, 0x6f, 0x74, 0xde, 0xeb, 0xd4, 0xa0, 0x17, 0x8f, 0x61, 0x5e, 0x5a, 0x0a, 0xe6, 0xd3, 0x6e, 0xc6, 0x01, 0x13, 0xc7, 0x82, 0x78, 0x0e, 0x33, 0xe7, 0x0b, 0x1f, 0x5c, 0x7c, 0xc8, 0x6f, 0x5a, 0x30, 0xf7, 0x94, 0x4b, 0x6a, 0x7f, 0x25, 0x12, 0x38, 0xaa, 0x49, 0x73, 0xbc, 0x4c, 0x01, 0xa6, 0x5c, 0xab, 0xe5, 0x06, 0x8e, 0x87, 0x17, 0xbd, 0xdb, 0x19, 0x12, 0xdf, 0x60, 0xf6, 0xa1, 0xbd, 0xa4, 0x0b, 0x14, 0xe9, 0xbf, 0x53, 0xee, 0x7f, 0x97, 0xd5, 0x8b, 0xff, 0x50, 0xf6, 0xdb, 0x4c, 0xee, 0x9c, 0xe4, 0x5f, 0x5f, 0x96, 0x95, 0xff, 0x1e, 0x36, 0x52, 0x53, 0x93, 0x35, 0x95, 0xb6, 0xe4, 0xe8, 0xdc, 0x67, 0x0d, 0xe9, 0xcc, 0x1a, 0x9d, 0x8d, 0x98, 0x6c, 0xc0, 0x6c, 0x66, 0xbc, 0xaa, 0x57, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x2b, 0x2e, 0xad, 0x5d, 0x11, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // KeyVaultAgentClient is the client API for KeyVaultAgent service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type KeyVaultAgentClient interface { Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) } type keyVaultAgentClient struct { cc *grpc.ClientConn } func NewKeyVaultAgentClient(cc *grpc.ClientConn) KeyVaultAgentClient { return &keyVaultAgentClient{cc} } func (c *keyVaultAgentClient) Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) { out := new(KeyVaultResponse) err := c.cc.Invoke(ctx, "/moc.cloudagent.security.KeyVaultAgent/Invoke", in, out, opts...) if err != nil { return nil, err } return out, nil } // KeyVaultAgentServer is the server API for KeyVaultAgent service. type KeyVaultAgentServer interface { Invoke(context.Context, *KeyVaultRequest) (*KeyVaultResponse, error) } // UnimplementedKeyVaultAgentServer can be embedded to have forward compatible implementations. type UnimplementedKeyVaultAgentServer struct { } func (*UnimplementedKeyVaultAgentServer) Invoke(ctx context.Context, req *KeyVaultRequest) (*KeyVaultResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Invoke not implemented") } func RegisterKeyVaultAgentServer(s *grpc.Server, srv KeyVaultAgentServer) { s.RegisterService(&_KeyVaultAgent_serviceDesc, srv) } func _KeyVaultAgent_Invoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KeyVaultRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(KeyVaultAgentServer).Invoke(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/moc.cloudagent.security.KeyVaultAgent/Invoke", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(KeyVaultAgentServer).Invoke(ctx, req.(*KeyVaultRequest)) } return interceptor(ctx, in, info, handler) } var _KeyVaultAgent_serviceDesc = grpc.ServiceDesc{ ServiceName: "moc.cloudagent.security.KeyVaultAgent", HandlerType: (*KeyVaultAgentServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Invoke", Handler: _KeyVaultAgent_Invoke_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "keyvault.proto", }
Reset
identifier_name
types.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /// <amd-module name="@angular/language-service/src/types" /> import { CompileDirectiveMetadata, CompileMetadataResolver, CompilePipeSummary, NgAnalyzedModules, StaticSymbol } from '@angular/compiler'; import { BuiltinType, DeclarationKind, Definition, PipeInfo, Pipes, Signature, Span, Symbol, SymbolDeclaration, SymbolQuery, SymbolTable } from '@angular/compiler-cli/src/language_services'; export { BuiltinType, DeclarationKind, Definition, PipeInfo, Pipes, Signature, Span, Symbol, SymbolDeclaration, SymbolQuery, SymbolTable };
* * A host interface; see `LanguageSeriviceHost`. * * @publicApi */ export interface TemplateSource { /** * The source of the template. */ readonly source: string; /** * The version of the source. As files are modified the version should change. That is, if the * `LanguageService` requesting template information for a source file and that file has changed * since the last time the host was asked for the file then this version string should be * different. No assumptions are made about the format of this string. * * The version can change more often than the source but should not change less often. */ readonly version: string; /** * The span of the template within the source file. */ readonly span: Span; /** * A static symbol for the template's component. */ readonly type: StaticSymbol; /** * The `SymbolTable` for the members of the component. */ readonly members: SymbolTable; /** * A `SymbolQuery` for the context of the template. */ readonly query: SymbolQuery; } /** * A sequence of template sources. * * A host type; see `LanguageSeriviceHost`. * * @publicApi */ export declare type TemplateSources = TemplateSource[] | undefined; /** * Error information found getting declaration information * * A host type; see `LanguageServiceHost`. * * @publicApi */ export interface DeclarationError { /** * The span of the error in the declaration's module. */ readonly span: Span; /** * The message to display describing the error or a chain * of messages. */ readonly message: string | DiagnosticMessageChain; } /** * Information about the component declarations. * * A file might contain a declaration without a template because the file contains only * templateUrl references. However, the compoennt declaration might contain errors that * need to be reported such as the template string is missing or the component is not * declared in a module. These error should be reported on the declaration, not the * template. * * A host type; see `LanguageSeriviceHost`. * * @publicApi */ export interface Declaration { /** * The static symbol of the compponent being declared. */ readonly type: StaticSymbol; /** * The span of the declaration annotation reference (e.g. the 'Component' or 'Directive' * reference). */ readonly declarationSpan: Span; /** * Reference to the compiler directive metadata for the declaration. */ readonly metadata?: CompileDirectiveMetadata; /** * Error reported trying to get the metadata. */ readonly errors: DeclarationError[]; } /** * A sequence of declarations. * * A host type; see `LanguageSeriviceHost`. * * @publicApi */ export declare type Declarations = Declaration[]; /** * The host for a `LanguageService`. This provides all the `LanguageService` requires to respond * to * the `LanguageService` requests. * * This interface describes the requirements of the `LanguageService` on its host. * * The host interface is host language agnostic. * * Adding optional member to this interface or any interface that is described as a * `LanguageServiceHost` interface is not considered a breaking change as defined by SemVer. * Removing a method or changing a member from required to optional will also not be considered a * breaking change. * * If a member is deprecated it will be changed to optional in a minor release before it is * removed in a major release. * * Adding a required member or changing a method's parameters, is considered a breaking change and * will only be done when breaking changes are allowed. When possible, a new optional member will * be added and the old member will be deprecated. The new member will then be made required in * and the old member will be removed only when breaking changes are allowed. * * While an interface is marked as experimental breaking-changes will be allowed between minor * releases. After an interface is marked as stable breaking-changes will only be allowed between * major releases. No breaking changes are allowed between patch releases. * * @publicApi */ export interface LanguageServiceHost { /** * The resolver to use to find compiler metadata. */ readonly resolver: CompileMetadataResolver; /** * Returns the template information for templates in `fileName` at the given location. If * `fileName` refers to a template file then the `position` should be ignored. If the `position` * is not in a template literal string then this method should return `undefined`. */ getTemplateAt(fileName: string, position: number): TemplateSource | undefined; /** * Return the template source information for all templates in `fileName` or for `fileName` if * it * is a template file. */ getTemplates(fileName: string): TemplateSources; /** * Returns the Angular declarations in the given file. */ getDeclarations(fileName: string): Declarations; /** * Return a summary of all Angular modules in the project. */ getAnalyzedModules(): NgAnalyzedModules; /** * Return a list all the template files referenced by the project. */ getTemplateReferences(): string[]; } /** * An item of the completion result to be displayed by an editor. * * A `LanguageService` interface. * * @publicApi */ export interface Completion { /** * The kind of comletion. */ kind: DeclarationKind; /** * The name of the completion to be displayed */ name: string; /** * The key to use to sort the completions for display. */ sort: string; } /** * A sequence of completions. * * @publicApi */ export declare type Completions = Completion[] | undefined; /** * A file and span. */ export interface Location { fileName: string; span: Span; } /** * The kind of diagnostic message. * * @publicApi */ export declare enum DiagnosticKind { Error = 0, Warning = 1 } /** * A template diagnostics message chain. This is similar to the TypeScript * DiagnosticMessageChain. The messages are intended to be formatted as separate * sentence fragments and indented. * * For compatibility previous implementation, the values are expected to override * toString() to return a formatted message. * * @publicApi */ export interface DiagnosticMessageChain { /** * The text of the diagnostic message to display. */ message: string; /** * The next message in the chain. */ next?: DiagnosticMessageChain; } /** * An template diagnostic message to display. * * @publicApi */ export interface Diagnostic { /** * The kind of diagnostic message */ kind: DiagnosticKind; /** * The source span that should be highlighted. */ span: Span; /** * The text of the diagnostic message to display or a chain of messages. */ message: string | DiagnosticMessageChain; } /** * A sequence of diagnostic message. * * @publicApi */ export declare type Diagnostics = Diagnostic[]; /** * A section of hover text. If the text is code then language should be provided. * Otherwise the text is assumed to be Markdown text that will be sanitized. */ export interface HoverTextSection { /** * Source code or markdown text describing the symbol a the hover location. */ readonly text: string; /** * The language of the source if `text` is a source code fragment. */ readonly language?: string; } /** * Hover information for a symbol at the hover location. */ export interface Hover { /** * The hover text to display for the symbol at the hover location. If the text includes * source code, the section will specify which language it should be interpreted as. */ readonly text: HoverTextSection[]; /** * The span of source the hover covers. */ readonly span: Span; } /** * An instance of an Angular language service created by `createLanguageService()`. * * The language service returns information about Angular templates that are included in a project * as defined by the `LanguageServiceHost`. * * When a method expects a `fileName` this file can either be source file in the project that * contains a template in a string literal or a template file referenced by the project returned * by `getTemplateReference()`. All other files will cause the method to return `undefined`. * * If a method takes a `position`, it is the offset of the UTF-16 code-point relative to the * beginning of the file reference by `fileName`. * * This interface and all interfaces and types marked as `LanguageService` types, describe a * particlar implementation of the Angular language service and is not intented to be * implemented. Adding members to the interface will not be considered a breaking change as * defined by SemVer. * * Removing a member or making a member optional, changing a method parameters, or changing a * member's type will all be considered a breaking change. * * While an interface is marked as experimental breaking-changes will be allowed between minor * releases. After an interface is marked as stable breaking-changes will only be allowed between * major releases. No breaking changes are allowed between patch releases. * * @publicApi */ export interface LanguageService { /** * Returns a list of all the external templates referenced by the project. */ getTemplateReferences(): string[] | undefined; /** * Returns a list of all error for all templates in the given file. */ getDiagnostics(fileName: string): Diagnostics | undefined; /** * Return the completions at the given position. */ getCompletionsAt(fileName: string, position: number): Completions | undefined; /** * Return the definition location for the symbol at position. */ getDefinitionAt(fileName: string, position: number): Definition | undefined; /** * Return the hover information for the symbol at position. */ getHoverAt(fileName: string, position: number): Hover | undefined; /** * Return the pipes that are available at the given position. */ getPipesAt(fileName: string, position: number): CompilePipeSummary[]; }
/** * The information `LanguageService` needs from the `LanguageServiceHost` to describe the content of * a template and the language context the template is in.
random_line_split
assets.js
if (typeof(Perch) == 'undefined') { Perch = {}; Perch.UI = {}; Perch.Apps = {}; } Perch.UI.Assets = function() { var selected_asset = false; var target_field = false; var target_group_id = false; var target_bucket = 'default'; var current_page = 1; var last_request_page = 0; var current_opts = {}; var orig_opts = {}; var w = $(window); var asset_index = []; var spinner; var spinning = false; var init = function() { $('body').addClass('js'); $.ajaxSetup({ cache: true, data: { "v": Perch.version } }); init_asset_badge(); init_asset_chooser(); init_tag_fields(); }; var init_asset_badge = function(badge) { if (!badge) var badge = $('.asset-badge'); badge.on('change', 'input[type=checkbox]', function(e){ var self = $(this); var cont = self.parents('.asset-badge').find('.asset-badge-thumb'); if (self.is(':checked')) { cont.addClass('asset-strikethrough'); }else{ cont.removeClass('asset-strikethrough'); } }); }; var init_asset_chooser = function() { var placeholder = $('.ft-choose-asset:not(.assets-disabled)'); if (placeholder.length) { head.ready(['lang'], function(){ var label = Perch.Lang.get('Select or upload an image'); if (placeholder.is('.ft-file')) { label = Perch.Lang.get('Select or upload a file'); } placeholder.html('<a href="#" class="disabled">'+label+'</a>'); }); head.ready(['lang', 'privs'], function(){ placeholder.find('a.disabled').removeClass('disabled'); }); $('form').on('click', '.ft-choose-asset:not(.assets-disabled) a', function(e){ e.preventDefault(); var link = $(this); if (link.is('.disabled')) return; var self = link.parent('.ft-choose-asset'); target_field = self.attr('data-field'); target_group_id = self.attr('data-input'); target_bucket = self.attr('data-bucket'); open_asset_chooser(self.attr('data-type')); }); placeholder.parents('.field').find('input[type=file]').hide(); head.ready(['lang', 'privs'], function(){ load_templates(function(){ init_asset_panel(); }); }); placeholder.parents('.field-wrap').css('vertical-align', 'top'); } }; var init_asset_panel = function() { var template = Handlebars.templates['asset-chooser']; $('.main').before(template({ upload_url: Perch.path+'/core/apps/assets/upload/' })); $('.asset-chooser').hide(); $('.asset-field').on('click', '.alert .action', function(e){ e.preventDefault(); current_opts = {view: current_opts.view};// jQuery.extend(true, {}, orig_opts); filter_asset_field($('#asset-filter')); }); $.getScript(Perch.path+'/core/assets/js/jquery.slimscroll.min.js', function(){ var wh = $(window).height(); var bh = $('body').height(); $('.asset-field .inner').slimScroll({ height: (wh-160)+'px', railVisible: true, alwaysVisible: true, }).bind('slimscroll', function(e, pos){ if (pos=='bottom') { get_assets(current_opts, populate_chooser); } }); $('.asset-chooser').css('height', bh+20); }); $('.asset-field').on('click keypress', '.grid-asset, .list-asset-title', function(e){ e.preventDefault(); var t = $(e.target); if (!t.is('.list-asset-title')) { if (!t.is('.grid-asset')) { t = t.parents('.grid-asset'); } } select_grid_asset(t); }); $('.asset-field').on('dblclick', '.grid-asset, .list-asset-title', function(e){ e.preventDefault(); var t = $(e.target); if (!t.is('.list-asset-title')) { if (!t.is('.grid-asset')) { t = t.parents('.grid-asset'); select_grid_asset(t); var item = asset_index[selected_asset]; update_form_with_selected_asset(item); close_asset_chooser(); w.trigger('Perch.asset_deselected'); selected_asset = false; target_field = false; target_group_id = false; } } }); w.on('Perch.asset_selected', function(){ $('.asset-topbar .actions .select').addClass('active'); }); w.on('Perch.asset_deselected', function(){ $('.asset-topbar .actions .select').removeClass('active'); }); $('.asset-topbar').on('click', '.select.active', function(e){ e.preventDefault(); var item = asset_index[selected_asset]; update_form_with_selected_asset(item); close_asset_chooser(); w.trigger('Perch.asset_deselected'); selected_asset = false; target_field = false; target_group_id = false; }); $('.asset-topbar').on('click', '.add', function(e){ e.preventDefault(); w.trigger('Perch.asset_deselected'); if ($('.asset-drop').is('.open')) { close_asset_drop(); }else{ open_asset_drop(); }
e.preventDefault(); w.trigger('Perch.asset_deselected'); close_asset_chooser(); }); $.getScript(Perch.path+'/core/assets/js/dropzone.js'); $.getScript(Perch.path+'/core/assets/js/spin.min.js'); $.ajax({ url: Perch.path+'/core/apps/assets/async/asset-filter.php', cache: false, success: function(r){ var container = $('#asset-filter'); container.append(r); container.on('click', 'a:not(.action)', function(e){ var target = $(e.target); var li = target.parent('li'); var ul = li.parent('ul'); if (ul.is('.open') && (li!=ul.find('li').first())) { e.preventDefault(); }else{ e.preventDefault(); filter_asset_field(container, target.attr('href')); } }); container.on('submit', 'form', function(e){ e.preventDefault(); var field = $(e.target).find('input.search'); filter_asset_field(container, '?q='+field.val()); }); } }); }; var filter_asset_field = function(container, href) { if (!href) href = ''; if (href) { href.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { current_opts[$1] = $3; } ); } $.ajax({ url: Perch.path+'/core/apps/assets/async/asset-filter.php', data: current_opts, success: function(r){ container.html(r); Perch.UI.Global.initSmartBar(container); } }); reload_assets(); } var open_asset_drop = function() { var drop = $('.asset-drop'); var form = drop.find('form'); drop.animate({height: '220px'}).addClass('open'); $('.asset-field').animate({top:'60px'}); var load_progress = 0; if (!drop.is('.dropzone')) { var reload_done = false; drop.addClass('dropzone'); form.addClass('dropzone'); form.dropzone({ clickable: true, dictDefaultMessage: Perch.Lang.get('Drop files here or click to upload'), uploadMultiple: false, totaluploadprogress: function(p) { load_progress = p; }, success: function(y, serverResponse) { if (load_progress==100) { close_asset_drop(); if (serverResponse.type) current_opts.type = serverResponse.type; if (!reload_done){ reload_done = true; reload_assets(); } } }, fallback: function(){ $.getScript(Perch.path+'/core/assets/js/jquery.form.min.js', function(){ form.ajaxForm({ beforeSubmit: function(){ show_spinner(); }, success: function(r) { hide_spinner(); close_asset_drop(); reload_assets(); } }); }); }, sending: function(file, xhr, formData){ formData.append('bucket', target_bucket); }, complete: function(file){ this.removeFile(file); }, //forceFallback: true, // useful for testing! }); } }; var close_asset_drop = function() { $('.asset-drop').animate({height: '0'}).removeClass('open'); $('.asset-field').animate({top:'60px'}); }; var open_asset_chooser = function(type) { var body = $('body'); if (body.hasClass('sidebar-open')) { body.removeClass('sidebar-open').addClass('sidebar-closed'); } $('.asset-chooser').addClass('transitioning').show().animate({'width': '744px'}, function(){ $('.main').one('click', close_asset_chooser); current_opts = {'type': type, 'bucket': target_bucket}; orig_opts = jQuery.extend(true, {}, current_opts); if (asset_index.length==0) get_assets(current_opts, populate_chooser); $('.asset-chooser').removeClass('transitioning'); }); $('.main, .topbar, .submit.stuck').animate({'left': '-800px', 'right': '800px'}); $('.main').addClass('asset-chooser-open'); Perch.UI.Global.initSmartBar($('#asset-filter')); $('.metanav').on('click', '.logout', function(e){ e.preventDefault(); close_asset_chooser(); }); }; var close_asset_chooser = function() { $('.asset-chooser').addClass('transitioning').animate({'width': '0'}, function(){ $(this).hide(); }); $('.main').animate({'left': '0'}); $('.topbar, .submit.stuck').animate({'left': '0', 'right': '55px'}, function(){ $('.topbar').css('right', ''); }); $('.main').removeClass('asset-chooser-open').unbind('click', close_asset_chooser); $('.metanav').unbind(); }; var select_grid_asset = function(item) { selected_asset = item.attr('data-id'); if (item.is('.selected')) { $('.asset-field .selected').removeClass('selected'); w.trigger('Perch.asset_deselected'); selected_asset = false }else{ $('.asset-field .selected').removeClass('selected'); item.addClass('selected'); w.trigger('Perch.asset_selected'); } }; var load_templates = function(callback) { $.getScript(Perch.path+'/core/assets/js/handlebars.runtime.js', function(){ $.getScript(Perch.path+'/core/assets/js/templates.js', function(){ callback(); }); Handlebars.registerHelper('Lang', function(str) { return Perch.Lang.get(str); }); Handlebars.registerHelper('hasPriv', function(str, block) { if (Perch.Privs.has(str)>=0) { return block.fn(this); } }); }); }; var get_assets = function(opts, callback) { var cb = function(callback) { return function(result) { last_request_page = current_page; if (result.assets.length) { var i, l; for(i=0, l=result.assets.length; i<l; i++) { asset_index[result.assets[i].id] = result.assets[i]; } current_page++; } callback(result); }; }; if (current_page>last_request_page) { show_spinner(); $.ajax({ dataType: 'json', url: Perch.path+'/core/apps/assets/async/get-assets.php?page='+current_page, data: opts, success: cb(callback), cache: false }); } }; var reload_assets = function() { current_page = 1; last_request_page = 0; asset_index = []; $('.grid-asset, .list-asset').remove(); get_assets(current_opts, populate_chooser); } var populate_chooser = function(data) { if (current_opts['view'] && current_opts['view']=='list') { var template = Handlebars.templates['asset-list']; }else{ var template = Handlebars.templates['asset-grid']; } var target = $('.asset-field .inner'); target.find('.notice').remove(); hide_spinner(); if (current_page>1 && !data.assets.length) return; target.append(template(data)); } var show_spinner = function() { if (!spinner) spinner = new Spinner().spin($('.asset-field').get(0)); }; var hide_spinner = function() { if (spinner) { spinner.stop(); spinner = false; } } var update_form_with_selected_asset = function(item) { var field = $('#'+target_field); field.val(item.id); var data = item; data.asset_field = target_field; data.input_id = target_group_id; var template = Handlebars.templates['asset-badge']; $('.asset-badge[data-for='+target_field+']').replaceWith(template(data)); init_asset_badge($('.asset-badge[data-for='+target_field+']')); }; var init_tag_fields = function() { var fields = $('input[data-tags]'); if (fields.length) { $("<link/>", { rel: 'stylesheet', type: 'text/css', href: Perch.path+'/core/assets/css/jquery.tagsinput.css' }).appendTo('head'); $.getScript(Perch.path+'/core/assets/js/jquery.tagsinput.min.js', function(){ reinit_tag_fields(fields); }); } }; var reinit_tag_fields = function(fields) { if (!fields) fields = $('input[data-tags]'); fields.each(function(i, o){ var self = $(o); self.tagsInput({ autocomplete_url: Perch.path+self.attr('data-tags'), width: '340px', defaultText: Perch.Lang.get('Add a tag'), interactive: true, }); }); }; return { init: init }; }(); if (typeof(jQuery)!='undefined') { jQuery(function($) { Perch.UI.Assets.init(); }); }
}); $('.asset-topbar .close').on('click', function(e){
random_line_split
assets.js
if (typeof(Perch) == 'undefined') { Perch = {}; Perch.UI = {}; Perch.Apps = {}; } Perch.UI.Assets = function() { var selected_asset = false; var target_field = false; var target_group_id = false; var target_bucket = 'default'; var current_page = 1; var last_request_page = 0; var current_opts = {}; var orig_opts = {}; var w = $(window); var asset_index = []; var spinner; var spinning = false; var init = function() { $('body').addClass('js'); $.ajaxSetup({ cache: true, data: { "v": Perch.version } }); init_asset_badge(); init_asset_chooser(); init_tag_fields(); }; var init_asset_badge = function(badge) { if (!badge) var badge = $('.asset-badge'); badge.on('change', 'input[type=checkbox]', function(e){ var self = $(this); var cont = self.parents('.asset-badge').find('.asset-badge-thumb'); if (self.is(':checked')) { cont.addClass('asset-strikethrough'); }else{ cont.removeClass('asset-strikethrough'); } }); }; var init_asset_chooser = function() { var placeholder = $('.ft-choose-asset:not(.assets-disabled)'); if (placeholder.length) { head.ready(['lang'], function(){ var label = Perch.Lang.get('Select or upload an image'); if (placeholder.is('.ft-file')) { label = Perch.Lang.get('Select or upload a file'); } placeholder.html('<a href="#" class="disabled">'+label+'</a>'); }); head.ready(['lang', 'privs'], function(){ placeholder.find('a.disabled').removeClass('disabled'); }); $('form').on('click', '.ft-choose-asset:not(.assets-disabled) a', function(e){ e.preventDefault(); var link = $(this); if (link.is('.disabled')) return; var self = link.parent('.ft-choose-asset'); target_field = self.attr('data-field'); target_group_id = self.attr('data-input'); target_bucket = self.attr('data-bucket'); open_asset_chooser(self.attr('data-type')); }); placeholder.parents('.field').find('input[type=file]').hide(); head.ready(['lang', 'privs'], function(){ load_templates(function(){ init_asset_panel(); }); }); placeholder.parents('.field-wrap').css('vertical-align', 'top'); } }; var init_asset_panel = function() { var template = Handlebars.templates['asset-chooser']; $('.main').before(template({ upload_url: Perch.path+'/core/apps/assets/upload/' })); $('.asset-chooser').hide(); $('.asset-field').on('click', '.alert .action', function(e){ e.preventDefault(); current_opts = {view: current_opts.view};// jQuery.extend(true, {}, orig_opts); filter_asset_field($('#asset-filter')); }); $.getScript(Perch.path+'/core/assets/js/jquery.slimscroll.min.js', function(){ var wh = $(window).height(); var bh = $('body').height(); $('.asset-field .inner').slimScroll({ height: (wh-160)+'px', railVisible: true, alwaysVisible: true, }).bind('slimscroll', function(e, pos){ if (pos=='bottom') { get_assets(current_opts, populate_chooser); } }); $('.asset-chooser').css('height', bh+20); }); $('.asset-field').on('click keypress', '.grid-asset, .list-asset-title', function(e){ e.preventDefault(); var t = $(e.target); if (!t.is('.list-asset-title')) { if (!t.is('.grid-asset')) { t = t.parents('.grid-asset'); } } select_grid_asset(t); }); $('.asset-field').on('dblclick', '.grid-asset, .list-asset-title', function(e){ e.preventDefault(); var t = $(e.target); if (!t.is('.list-asset-title')) { if (!t.is('.grid-asset')) { t = t.parents('.grid-asset'); select_grid_asset(t); var item = asset_index[selected_asset]; update_form_with_selected_asset(item); close_asset_chooser(); w.trigger('Perch.asset_deselected'); selected_asset = false; target_field = false; target_group_id = false; } } }); w.on('Perch.asset_selected', function(){ $('.asset-topbar .actions .select').addClass('active'); }); w.on('Perch.asset_deselected', function(){ $('.asset-topbar .actions .select').removeClass('active'); }); $('.asset-topbar').on('click', '.select.active', function(e){ e.preventDefault(); var item = asset_index[selected_asset]; update_form_with_selected_asset(item); close_asset_chooser(); w.trigger('Perch.asset_deselected'); selected_asset = false; target_field = false; target_group_id = false; }); $('.asset-topbar').on('click', '.add', function(e){ e.preventDefault(); w.trigger('Perch.asset_deselected'); if ($('.asset-drop').is('.open')) { close_asset_drop(); }else{ open_asset_drop(); } }); $('.asset-topbar .close').on('click', function(e){ e.preventDefault(); w.trigger('Perch.asset_deselected'); close_asset_chooser(); }); $.getScript(Perch.path+'/core/assets/js/dropzone.js'); $.getScript(Perch.path+'/core/assets/js/spin.min.js'); $.ajax({ url: Perch.path+'/core/apps/assets/async/asset-filter.php', cache: false, success: function(r){ var container = $('#asset-filter'); container.append(r); container.on('click', 'a:not(.action)', function(e){ var target = $(e.target); var li = target.parent('li'); var ul = li.parent('ul'); if (ul.is('.open') && (li!=ul.find('li').first())) { e.preventDefault(); }else{ e.preventDefault(); filter_asset_field(container, target.attr('href')); } }); container.on('submit', 'form', function(e){ e.preventDefault(); var field = $(e.target).find('input.search'); filter_asset_field(container, '?q='+field.val()); }); } }); }; var filter_asset_field = function(container, href) { if (!href) href = ''; if (href) { href.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { current_opts[$1] = $3; } ); } $.ajax({ url: Perch.path+'/core/apps/assets/async/asset-filter.php', data: current_opts, success: function(r){ container.html(r); Perch.UI.Global.initSmartBar(container); } }); reload_assets(); } var open_asset_drop = function() { var drop = $('.asset-drop'); var form = drop.find('form'); drop.animate({height: '220px'}).addClass('open'); $('.asset-field').animate({top:'60px'}); var load_progress = 0; if (!drop.is('.dropzone')) { var reload_done = false; drop.addClass('dropzone'); form.addClass('dropzone'); form.dropzone({ clickable: true, dictDefaultMessage: Perch.Lang.get('Drop files here or click to upload'), uploadMultiple: false, totaluploadprogress: function(p) { load_progress = p; }, success: function(y, serverResponse) { if (load_progress==100) { close_asset_drop(); if (serverResponse.type) current_opts.type = serverResponse.type; if (!reload_done){ reload_done = true; reload_assets(); } } }, fallback: function(){ $.getScript(Perch.path+'/core/assets/js/jquery.form.min.js', function(){ form.ajaxForm({ beforeSubmit: function(){ show_spinner(); }, success: function(r) { hide_spinner(); close_asset_drop(); reload_assets(); } }); }); }, sending: function(file, xhr, formData){ formData.append('bucket', target_bucket); }, complete: function(file){ this.removeFile(file); }, //forceFallback: true, // useful for testing! }); } }; var close_asset_drop = function() { $('.asset-drop').animate({height: '0'}).removeClass('open'); $('.asset-field').animate({top:'60px'}); }; var open_asset_chooser = function(type) { var body = $('body'); if (body.hasClass('sidebar-open')) { body.removeClass('sidebar-open').addClass('sidebar-closed'); } $('.asset-chooser').addClass('transitioning').show().animate({'width': '744px'}, function(){ $('.main').one('click', close_asset_chooser); current_opts = {'type': type, 'bucket': target_bucket}; orig_opts = jQuery.extend(true, {}, current_opts); if (asset_index.length==0) get_assets(current_opts, populate_chooser); $('.asset-chooser').removeClass('transitioning'); }); $('.main, .topbar, .submit.stuck').animate({'left': '-800px', 'right': '800px'}); $('.main').addClass('asset-chooser-open'); Perch.UI.Global.initSmartBar($('#asset-filter')); $('.metanav').on('click', '.logout', function(e){ e.preventDefault(); close_asset_chooser(); }); }; var close_asset_chooser = function() { $('.asset-chooser').addClass('transitioning').animate({'width': '0'}, function(){ $(this).hide(); }); $('.main').animate({'left': '0'}); $('.topbar, .submit.stuck').animate({'left': '0', 'right': '55px'}, function(){ $('.topbar').css('right', ''); }); $('.main').removeClass('asset-chooser-open').unbind('click', close_asset_chooser); $('.metanav').unbind(); }; var select_grid_asset = function(item) { selected_asset = item.attr('data-id'); if (item.is('.selected')) { $('.asset-field .selected').removeClass('selected'); w.trigger('Perch.asset_deselected'); selected_asset = false }else{ $('.asset-field .selected').removeClass('selected'); item.addClass('selected'); w.trigger('Perch.asset_selected'); } }; var load_templates = function(callback) { $.getScript(Perch.path+'/core/assets/js/handlebars.runtime.js', function(){ $.getScript(Perch.path+'/core/assets/js/templates.js', function(){ callback(); }); Handlebars.registerHelper('Lang', function(str) { return Perch.Lang.get(str); }); Handlebars.registerHelper('hasPriv', function(str, block) { if (Perch.Privs.has(str)>=0) { return block.fn(this); } }); }); }; var get_assets = function(opts, callback) { var cb = function(callback) { return function(result) { last_request_page = current_page; if (result.assets.length)
callback(result); }; }; if (current_page>last_request_page) { show_spinner(); $.ajax({ dataType: 'json', url: Perch.path+'/core/apps/assets/async/get-assets.php?page='+current_page, data: opts, success: cb(callback), cache: false }); } }; var reload_assets = function() { current_page = 1; last_request_page = 0; asset_index = []; $('.grid-asset, .list-asset').remove(); get_assets(current_opts, populate_chooser); } var populate_chooser = function(data) { if (current_opts['view'] && current_opts['view']=='list') { var template = Handlebars.templates['asset-list']; }else{ var template = Handlebars.templates['asset-grid']; } var target = $('.asset-field .inner'); target.find('.notice').remove(); hide_spinner(); if (current_page>1 && !data.assets.length) return; target.append(template(data)); } var show_spinner = function() { if (!spinner) spinner = new Spinner().spin($('.asset-field').get(0)); }; var hide_spinner = function() { if (spinner) { spinner.stop(); spinner = false; } } var update_form_with_selected_asset = function(item) { var field = $('#'+target_field); field.val(item.id); var data = item; data.asset_field = target_field; data.input_id = target_group_id; var template = Handlebars.templates['asset-badge']; $('.asset-badge[data-for='+target_field+']').replaceWith(template(data)); init_asset_badge($('.asset-badge[data-for='+target_field+']')); }; var init_tag_fields = function() { var fields = $('input[data-tags]'); if (fields.length) { $("<link/>", { rel: 'stylesheet', type: 'text/css', href: Perch.path+'/core/assets/css/jquery.tagsinput.css' }).appendTo('head'); $.getScript(Perch.path+'/core/assets/js/jquery.tagsinput.min.js', function(){ reinit_tag_fields(fields); }); } }; var reinit_tag_fields = function(fields) { if (!fields) fields = $('input[data-tags]'); fields.each(function(i, o){ var self = $(o); self.tagsInput({ autocomplete_url: Perch.path+self.attr('data-tags'), width: '340px', defaultText: Perch.Lang.get('Add a tag'), interactive: true, }); }); }; return { init: init }; }(); if (typeof(jQuery)!='undefined') { jQuery(function($) { Perch.UI.Assets.init(); }); }
{ var i, l; for(i=0, l=result.assets.length; i<l; i++) { asset_index[result.assets[i].id] = result.assets[i]; } current_page++; }
conditional_block
lib.rs
#![doc(html_root_url = "http://ogeon.github.io/docs/rust-wiringpi/master/")] #![cfg_attr(feature = "strict", deny(warnings))] extern crate libc; use std::marker::PhantomData; use pin::{Pin, Pwm, GpioClock, RequiresRoot}; macro_rules! impl_pins { ($($name:ident),+) => ( $( #[derive(Clone, Copy)] pub struct $name; impl Pin for $name {} )+ ) } macro_rules! impl_pwm { ($($name:ident: $pwm:expr),+) => ( $( impl Pwm for $name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] fn clock_pin() -> ClockPin<$name> { ClockPin::new($pwm) } } )+ ) } macro_rules! require_root { ($($name:ident),+) => ( $( impl RequiresRoot for $name {} )+ ) } mod bindings; pub mod thread { use bindings; use libc; ///This attempts to shift your program (or thread in a multi-threaded ///program) to a higher priority and enables a real-time scheduling. /// ///The priority parameter should be from 0 (the default) to 99 (the ///maximum). This won’t make your program go any faster, but it will give ///it a bigger slice of time when other programs are running. The priority ///parameter works relative to others – so you can make one program ///priority 1 and another priority 2 and it will have the same effect as ///setting one to 10 and the other to 90 (as long as no other programs are ///running with elevated priorities) /// ///The return value is `true` for success and `false` for error. If an ///error is returned, the program should then consult the _errno_ global ///variable, as per the usual conventions. /// ///_Note_: Only programs running as root can change their priority. If ///called from a non-root program then nothing happens. pub fn priority(priority: u8) -> bool { unsafe { bindings::piHiPri(priority as libc::c_int) >= 0 } } } pub mod pin { use bindings; use libc; use self::Value::{Low, High}; use std::marker::PhantomData; const INPUT: libc::c_int = 0; const OUTPUT: libc::c_int = 1; const PWM_OUTPUT: libc::c_int = 2; const GPIO_CLOCK: libc::c_int = 3; //const SOFT_PWM_OUTPUT: libc::c_int = 4; //const SOFT_TONE_OUTPUT: libc::c_int = 5; //const PWM_TONE_OUTPUT: libc::c_int = 6; ///This returns the BCM_GPIO pin number of the supplied **wiringPi** pin. /// ///It takes the board revision into account. pub fn wpi_to_gpio_number(wpi_number: u16) -> u16 { unsafe { bindings::wpiPinToGpio(wpi_number as libc::c_int) as u16 } } ///This returns the BCM_GPIO pin number of the supplied physical pin on ///the P1 connector. pub fn phys_to_gpio_number(phys_number: u16) -> u16 { unsafe { bindings::physPinToGpio(phys_number as libc::c_int) as u16 } } impl_pins!(WiringPi, Gpio, Phys, Sys); impl_pwm!(WiringPi: 1, Gpio: 18, Phys: 12); impl_clock!(WiringPi: 7, Gpio: 4, Phys: 7); require_root!(WiringPi, Gpio, Phys); pub trait Pin {} pub trait Pwm: RequiresRoot + Sized { fn pwm_pin() -> PwmPin<Self>; } pub trait GpioClock: RequiresRoot + Sized { fn clock_pin() -> ClockPin<Self>; } pub trait RequiresRoot: Pin {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Value { Low = 0, High } #[derive(Debug, Clone, Copy)] pub enum Edge { ///No setup is performed, it is assumed the trigger has already been set up previosuly Setup = 0, Falling = 1, Rising = 2, Both = 3 } #[derive(Debug, Clone, Copy)] pub enum Pull { Off = 0, Down, Up } #[derive(Debug, Clone, Copy)] pub enum PwmMode { MarkSpace = 0, Balanced } pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> InputPin<P> { pub fn new(pin: libc::c_int) -> InputPin<P> { unsafe { bindings::pinMode(pin, INPUT); } InputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &InputPin(number, _) = self; number } ///This function returns the value read at the given pin. /// ///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin. pub fn digital_read(&self) -> Value { let value = unsafe { bindings::digitalRead(self.number()) }; if value == 0 { Low } else {
} ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { bindings::analogRead(self.number()) as u16 } } /// This will register an "Interrupt" to be called when the pin changes state /// Note the quotes around Interrupt, because the current implementation in the C /// library seems to be a dedicated thread that polls the gpio device driver, /// and this callback is called from that thread synchronously, so it's not something that /// you would call a real interrupt in an embedded environement. /// /// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code. /// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for /// ideas on how to work around these limitations if you find them too constraining. /// /// ``` /// use wiringpi; /// /// extern "C" fn change_state() { /// println!("Look ma, I'm being called from an another thread"); /// } /// /// fn main() { /// let pi = wiringpi::setup(); /// let pin = pi.output_pin(0); /// /// pin.register_isr(Edge::Falling, Some(change_state)); /// /// thread::sleep(60000); /// } /// /// ``` /// /// pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) { unsafe { bindings::wiringPiISR(self.number(), edge as i32, f); } } } impl<P: Pin + RequiresRoot> InputPin<P> { ///This sets the pull-up or pull-down resistor mode on the given pin. /// ///Unlike the Arduino, the BCM2835 has both pull-up an down internal ///resistors. The parameter pud should be; `Off`, (no pull up/down), ///`Down` (pull to ground) or `Up` (pull to 3.3v) pub fn pull_up_dn_control(&self, pud: Pull) { unsafe { bindings::pullUpDnControl(self.number(), pud as libc::c_int); } } pub fn into_output(self) -> OutputPin<P> { let InputPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let InputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + Pwm> InputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let InputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> InputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let InputPin(number, _) = self; ClockPin::new(number) } } /// A pin with software controlled PWM output. /// /// Due to limitations of the chip only one pin is able to do /// hardware-controlled PWM output. The `SoftPwmPin`s on the /// other hand allow for all GPIOs to output PWM signals. /// /// The pulse width of the signal will be 100μs with a value range /// of [0,100] \(where `0` is a constant low and `100` is a /// constant high) resulting in a frequenzy of 100 Hz. /// /// **Important**: In order to use software PWM pins *wiringPi* /// has to be setup in GPIO mode via `setup_gpio()`. pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + RequiresRoot> SoftPwmPin<P> { /// Configures the given `pin` to output a software controlled PWM /// signal. pub fn new(pin: libc::c_int) -> SoftPwmPin<P> { unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { bindings::softPwmWrite(self.number(), value); } } /// Stops the software handling of this pin. /// /// _Note_: In order to control this pin via software PWM again /// it will need to be recreated using `new()`. pub fn pwm_stop(self) { unsafe { bindings::softPwmStop(self.number()); } } pub fn into_input(self) -> InputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); OutputPin::new(number) } } impl<P: Pin + Pwm> SoftPwmPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); PwmPin::new(number) } } impl<P: Pin + GpioClock> SoftPwmPin<P> { pub fn into_clock(self) -> ClockPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); ClockPin::new(number) } } pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> OutputPin<P> { pub fn new(pin: libc::c_int) -> OutputPin<P> { unsafe { bindings::pinMode(pin, OUTPUT); } OutputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &OutputPin(number, _) = self; number } ///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output. pub fn digital_write(&self, value: Value) { unsafe { bindings::digitalWrite(self.number(), value as libc::c_int); } } ///This writes the given value to the supplied analog pin. You will ///need to register additional analog modules to enable this function ///for devices such as the Gertboard. pub fn analog_write(&self, value: u16) { unsafe { bindings::analogWrite(self.number(), value as libc::c_int); } } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let OutputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_input(self) -> InputPin<P> { let OutputPin(number, _) = self; InputPin::new(number) } } impl<P: Pin + Pwm> OutputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let OutputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> OutputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let OutputPin(number, _) = self; ClockPin::new(number) } } ///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + Pwm> PwmPin<P> { pub fn new(pin: libc::c_int) -> PwmPin<P> { unsafe { bindings::pinMode(pin, PWM_OUTPUT); } PwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &PwmPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let PwmPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let PwmPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let PwmPin(number, _) = self; SoftPwmPin::new(number) } ///Writes the value to the PWM register for the given pin. /// ///The value must be between 0 and 1024. pub fn write(&self, value: u16) { unsafe { bindings::pwmWrite(self.number(), value as libc::c_int); } } ///The PWM generator can run in 2 modes – "balanced" and "mark:space". /// ///The mark:space mode is traditional, however the default mode in the ///Pi is "balanced". You can switch modes by supplying the parameter: ///`Balanced` or `MarkSpace`. pub fn set_mode(&self, mode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as libc::c_uint); } } ///This sets the divisor for the PWM clock. pub fn set_clock(&self, value: u16) { unsafe { bindings::pwmSetClock(value as libc::c_int); } } } pub struct ClockPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + GpioClock> ClockPin<P> { pub fn new(pin: libc::c_int) -> ClockPin<P> { unsafe { bindings::pinMode(pin, GPIO_CLOCK); } ClockPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &ClockPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let ClockPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let ClockPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let ClockPin(number, _) = self; SoftPwmPin::new(number) } ///Set the freuency on a GPIO clock pin. pub fn frequency(&self, freq: u16) { unsafe { bindings::gpioClockSet(self.number(), freq as libc::c_int); } } } } ///This initialises the wiringPi system and assumes that the calling program ///is going to be using the **wiringPi** pin numbering scheme. /// ///This is a simplified numbering scheme which provides a mapping from virtual ///pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. ///See the pins page for a table which maps the **wiringPi** pin number to the ///Broadcom GPIO pin number to the physical location on the edge connector. /// ///This function needs to be called with root privileges. pub fn setup() -> WiringPi<pin::WiringPi> { unsafe { bindings::wiringPiSetup(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the Broadcom GPIO pin numbers directly with no re-mapping. /// ///This function needs to be called with root privileges. pub fn setup_gpio() -> WiringPi<pin::Gpio> { unsafe { bindings::wiringPiSetupGpio(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the physical pin numbers _on the P1 connector only_. /// ///This function needs to be called with root privileges. pub fn setup_phys() -> WiringPi<pin::Phys> { unsafe { bindings::wiringPiSetupPhys(); } WiringPi(PhantomData) } ///This initialises the wiringPi system but uses the /sys/class/gpio interface ///rather than accessing the hardware directly. /// ///This can be called as a non-root user provided the GPIO pins have been ///exported before-hand using the gpio program. Pin number in this mode is the ///native Broadcom GPIO numbers. /// ///_Note_: In this mode you can only use the pins which have been exported via ///the /sys/class/gpio interface. You must export these pins before you call ///your program. You can do this in a separate shell-script, or by using the ///system() function from inside your program. /// ///Also note that some functions have no effect when using this mode as ///they’re not currently possible to action unless called with root ///privileges. pub fn setup_sys() -> WiringPi<pin::Sys> { unsafe { bindings::wiringPiSetupSys(); } WiringPi(PhantomData) } ///This returns the board revision of the Raspberry Pi. /// ///It will be either 1 or 2. Some of the BCM_GPIO pins changed number and ///function when moving from board revision 1 to 2, so if you are using ///BCM_GPIO pin numbers, then you need to be aware of the differences. pub fn board_revision() -> i32 { unsafe { bindings::piBoardRev() } } pub struct WiringPi<Pin>(PhantomData<Pin>); impl<P: Pin> WiringPi<P> { pub fn input_pin(&self, pin: u16) -> pin::InputPin<P> { let pin = pin as libc::c_int; pin::InputPin::new(pin) } pub fn output_pin(&self, pin: u16) -> pin::OutputPin<P> { let pin = pin as libc::c_int; pin::OutputPin::new(pin) } ///This returns a number representing the number if milliseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 49 days. pub fn millis(&self) -> u32 { unsafe { bindings::millis() } } ///This returns a number representing the number if microseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 71 minutes. pub fn micros(&self) -> u32 { unsafe { bindings::micros() } } ///This writes the 8-bit byte supplied to the first 8 GPIO pins. It’s the ///fastest way to set all 8 bits at once to a particular value, although ///it still takes two write operations to the Pi’s GPIO hardware. pub fn digital_write_byte(&self, byte: u8) { unsafe { bindings::digitalWriteByte(byte as libc::c_int); } } } impl<P: Pwm + Pin> WiringPi<P> { pub fn pwm_pin(&self) -> pin::PwmPin<P> { Pwm::pwm_pin() } } impl<P: GpioClock + Pin> WiringPi<P> { pub fn clock_pin(&self) -> pin::ClockPin<P> { GpioClock::clock_pin() } } impl<P: Pin + RequiresRoot> WiringPi<P> { pub fn soft_pwm_pin(&self, pin: u16) -> pin::SoftPwmPin<P> { let pin = pin as libc::c_int; pin::SoftPwmPin::new(pin) } }
High }
conditional_block
lib.rs
#![doc(html_root_url = "http://ogeon.github.io/docs/rust-wiringpi/master/")] #![cfg_attr(feature = "strict", deny(warnings))] extern crate libc; use std::marker::PhantomData; use pin::{Pin, Pwm, GpioClock, RequiresRoot}; macro_rules! impl_pins { ($($name:ident),+) => ( $( #[derive(Clone, Copy)] pub struct $name; impl Pin for $name {} )+ ) } macro_rules! impl_pwm { ($($name:ident: $pwm:expr),+) => ( $( impl Pwm for $name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] fn clock_pin() -> ClockPin<$name> { ClockPin::new($pwm) } } )+ ) } macro_rules! require_root { ($($name:ident),+) => ( $( impl RequiresRoot for $name {} )+ ) } mod bindings; pub mod thread { use bindings; use libc; ///This attempts to shift your program (or thread in a multi-threaded ///program) to a higher priority and enables a real-time scheduling. /// ///The priority parameter should be from 0 (the default) to 99 (the ///maximum). This won’t make your program go any faster, but it will give ///it a bigger slice of time when other programs are running. The priority ///parameter works relative to others – so you can make one program ///priority 1 and another priority 2 and it will have the same effect as ///setting one to 10 and the other to 90 (as long as no other programs are ///running with elevated priorities) /// ///The return value is `true` for success and `false` for error. If an ///error is returned, the program should then consult the _errno_ global ///variable, as per the usual conventions. /// ///_Note_: Only programs running as root can change their priority. If ///called from a non-root program then nothing happens. pub fn priority(priority: u8) -> bool { unsafe { bindings::piHiPri(priority as libc::c_int) >= 0 } } } pub mod pin { use bindings; use libc; use self::Value::{Low, High}; use std::marker::PhantomData; const INPUT: libc::c_int = 0; const OUTPUT: libc::c_int = 1; const PWM_OUTPUT: libc::c_int = 2; const GPIO_CLOCK: libc::c_int = 3; //const SOFT_PWM_OUTPUT: libc::c_int = 4; //const SOFT_TONE_OUTPUT: libc::c_int = 5; //const PWM_TONE_OUTPUT: libc::c_int = 6; ///This returns the BCM_GPIO pin number of the supplied **wiringPi** pin. /// ///It takes the board revision into account. pub fn wpi_to_gpio_number(wpi_number: u16) -> u16 { unsafe { bindings::wpiPinToGpio(wpi_number as libc::c_int) as u16 } } ///This returns the BCM_GPIO pin number of the supplied physical pin on ///the P1 connector. pub fn phys_to_gpio_number(phys_number: u16) -> u16 { unsafe { bindings::physPinToGpio(phys_number as libc::c_int) as u16 } } impl_pins!(WiringPi, Gpio, Phys, Sys); impl_pwm!(WiringPi: 1, Gpio: 18, Phys: 12); impl_clock!(WiringPi: 7, Gpio: 4, Phys: 7); require_root!(WiringPi, Gpio, Phys); pub trait Pin {} pub trait Pwm: RequiresRoot + Sized { fn pwm_pin() -> PwmPin<Self>; } pub trait GpioClock: RequiresRoot + Sized { fn clock_pin() -> ClockPin<Self>; } pub trait RequiresRoot: Pin {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Value { Low = 0, High } #[derive(Debug, Clone, Copy)] pub enum Edge { ///No setup is performed, it is assumed the trigger has already been set up previosuly Setup = 0, Falling = 1, Rising = 2, Both = 3 } #[derive(Debug, Clone, Copy)] pub enum Pull { Off = 0, Down, Up } #[derive(Debug, Clone, Copy)] pub enum PwmMode { MarkSpace = 0, Balanced } pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> InputPin<P> { pub fn new(pin: libc::c_int) -> InputPin<P> { unsafe { bindings::pinMode(pin, INPUT); } InputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &InputPin(number, _) = self; number } ///This function returns the value read at the given pin. /// ///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin. pub fn digital_read(&self) -> Value { let value = unsafe { bindings::digitalRead(self.number()) }; if value == 0 { Low } else { High } } ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { bindings::analogRead(self.number()) as u16 } } /// This will register an "Interrupt" to be called when the pin changes state /// Note the quotes around Interrupt, because the current implementation in the C /// library seems to be a dedicated thread that polls the gpio device driver, /// and this callback is called from that thread synchronously, so it's not something that /// you would call a real interrupt in an embedded environement. /// /// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code. /// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for /// ideas on how to work around these limitations if you find them too constraining. /// /// ``` /// use wiringpi; /// /// extern "C" fn change_state() { /// println!("Look ma, I'm being called from an another thread"); /// } /// /// fn main() { /// let pi = wiringpi::setup(); /// let pin = pi.output_pin(0); /// /// pin.register_isr(Edge::Falling, Some(change_state)); /// /// thread::sleep(60000); /// } /// /// ``` /// /// pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) { unsafe { bindings::wiringPiISR(self.number(), edge as i32, f); } } } impl<P: Pin + RequiresRoot> InputPin<P> { ///This sets the pull-up or pull-down resistor mode on the given pin. /// ///Unlike the Arduino, the BCM2835 has both pull-up an down internal ///resistors. The parameter pud should be; `Off`, (no pull up/down), ///`Down` (pull to ground) or `Up` (pull to 3.3v) pub fn pull_up_dn_control(&self, pud: Pull) { unsafe { bindings::pullUpDnControl(self.number(), pud as libc::c_int); } } pub fn into_output(self) -> OutputPin<P> { let InputPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let InputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + Pwm> InputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let InputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> InputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let InputPin(number, _) = self; ClockPin::new(number) } } /// A pin with software controlled PWM output. /// /// Due to limitations of the chip only one pin is able to do /// hardware-controlled PWM output. The `SoftPwmPin`s on the /// other hand allow for all GPIOs to output PWM signals. /// /// The pulse width of the signal will be 100μs with a value range /// of [0,100] \(where `0` is a constant low and `100` is a /// constant high) resulting in a frequenzy of 100 Hz. /// /// **Important**: In order to use software PWM pins *wiringPi* /// has to be setup in GPIO mode via `setup_gpio()`. pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + RequiresRoot> SoftPwmPin<P> { /// Configures the given `pin` to output a software controlled PWM /// signal. pub fn new(pin: libc::c_int) -> SoftPwmPin<P> { unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { bindings::softPwmWrite(self.number(), value); } } /// Stops the software handling of this pin. /// /// _Note_: In order to control this pin via software PWM again /// it will need to be recreated using `new()`. pub fn pwm_stop(self) { unsafe { bindings::softPwmStop(self.number()); } } pub fn into_input(self) -> InputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); OutputPin::new(number) } } impl<P: Pin + Pwm> SoftPwmPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); PwmPin::new(number) } } impl<P: Pin + GpioClock> SoftPwmPin<P> { pub fn into_clock(self) -> ClockPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); ClockPin::new(number) } } pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> OutputPin<P> { pub fn new(pin: libc::c_int) -> OutputPin<P> { unsafe { bindings::pinMode(pin, OUTPUT); } OutputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &OutputPin(number, _) = self; number } ///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output. pub fn digital_write(&self, value: Value) { unsafe { bindings::digitalWrite(self.number(), value as libc::c_int); } } ///This writes the given value to the supplied analog pin. You will ///need to register additional analog modules to enable this function ///for devices such as the Gertboard. pub fn analog_write(&self, value: u16) { unsafe { bindings::analogWrite(self.number(), value as libc::c_int); } } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let OutputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_input(self) -> InputPin<P> { let OutputPin(number, _) = self; InputPin::new(number) } } impl<P: Pin + Pwm> OutputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let OutputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> OutputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let OutputPin(number, _) = self; ClockPin::new(number) } } ///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + Pwm> PwmPin<P> { pub fn new(pin: libc::c_int) -> PwmPin<P> { unsafe { bindings::pinMode(pin, PWM_OUTPUT); } PwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &PwmPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let PwmPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let PwmPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let PwmPin(number, _) = self; SoftPwmPin::new(number) } ///Writes the value to the PWM register for the given pin. /// ///The value must be between 0 and 1024. pub fn write(&self, value: u16) { unsafe { bindings::pwmWrite(self.number(), value as libc::c_int); } } ///The PWM generator can run in 2 modes – "balanced" and "mark:space". /// ///The mark:space mode is traditional, however the default mode in the ///Pi is "balanced". You can switch modes by supplying the parameter: ///`Balanced` or `MarkSpace`. pub fn set_mode(
ode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as libc::c_uint); } } ///This sets the divisor for the PWM clock. pub fn set_clock(&self, value: u16) { unsafe { bindings::pwmSetClock(value as libc::c_int); } } } pub struct ClockPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + GpioClock> ClockPin<P> { pub fn new(pin: libc::c_int) -> ClockPin<P> { unsafe { bindings::pinMode(pin, GPIO_CLOCK); } ClockPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &ClockPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let ClockPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let ClockPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let ClockPin(number, _) = self; SoftPwmPin::new(number) } ///Set the freuency on a GPIO clock pin. pub fn frequency(&self, freq: u16) { unsafe { bindings::gpioClockSet(self.number(), freq as libc::c_int); } } } } ///This initialises the wiringPi system and assumes that the calling program ///is going to be using the **wiringPi** pin numbering scheme. /// ///This is a simplified numbering scheme which provides a mapping from virtual ///pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. ///See the pins page for a table which maps the **wiringPi** pin number to the ///Broadcom GPIO pin number to the physical location on the edge connector. /// ///This function needs to be called with root privileges. pub fn setup() -> WiringPi<pin::WiringPi> { unsafe { bindings::wiringPiSetup(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the Broadcom GPIO pin numbers directly with no re-mapping. /// ///This function needs to be called with root privileges. pub fn setup_gpio() -> WiringPi<pin::Gpio> { unsafe { bindings::wiringPiSetupGpio(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the physical pin numbers _on the P1 connector only_. /// ///This function needs to be called with root privileges. pub fn setup_phys() -> WiringPi<pin::Phys> { unsafe { bindings::wiringPiSetupPhys(); } WiringPi(PhantomData) } ///This initialises the wiringPi system but uses the /sys/class/gpio interface ///rather than accessing the hardware directly. /// ///This can be called as a non-root user provided the GPIO pins have been ///exported before-hand using the gpio program. Pin number in this mode is the ///native Broadcom GPIO numbers. /// ///_Note_: In this mode you can only use the pins which have been exported via ///the /sys/class/gpio interface. You must export these pins before you call ///your program. You can do this in a separate shell-script, or by using the ///system() function from inside your program. /// ///Also note that some functions have no effect when using this mode as ///they’re not currently possible to action unless called with root ///privileges. pub fn setup_sys() -> WiringPi<pin::Sys> { unsafe { bindings::wiringPiSetupSys(); } WiringPi(PhantomData) } ///This returns the board revision of the Raspberry Pi. /// ///It will be either 1 or 2. Some of the BCM_GPIO pins changed number and ///function when moving from board revision 1 to 2, so if you are using ///BCM_GPIO pin numbers, then you need to be aware of the differences. pub fn board_revision() -> i32 { unsafe { bindings::piBoardRev() } } pub struct WiringPi<Pin>(PhantomData<Pin>); impl<P: Pin> WiringPi<P> { pub fn input_pin(&self, pin: u16) -> pin::InputPin<P> { let pin = pin as libc::c_int; pin::InputPin::new(pin) } pub fn output_pin(&self, pin: u16) -> pin::OutputPin<P> { let pin = pin as libc::c_int; pin::OutputPin::new(pin) } ///This returns a number representing the number if milliseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 49 days. pub fn millis(&self) -> u32 { unsafe { bindings::millis() } } ///This returns a number representing the number if microseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 71 minutes. pub fn micros(&self) -> u32 { unsafe { bindings::micros() } } ///This writes the 8-bit byte supplied to the first 8 GPIO pins. It’s the ///fastest way to set all 8 bits at once to a particular value, although ///it still takes two write operations to the Pi’s GPIO hardware. pub fn digital_write_byte(&self, byte: u8) { unsafe { bindings::digitalWriteByte(byte as libc::c_int); } } } impl<P: Pwm + Pin> WiringPi<P> { pub fn pwm_pin(&self) -> pin::PwmPin<P> { Pwm::pwm_pin() } } impl<P: GpioClock + Pin> WiringPi<P> { pub fn clock_pin(&self) -> pin::ClockPin<P> { GpioClock::clock_pin() } } impl<P: Pin + RequiresRoot> WiringPi<P> { pub fn soft_pwm_pin(&self, pin: u16) -> pin::SoftPwmPin<P> { let pin = pin as libc::c_int; pin::SoftPwmPin::new(pin) } }
&self, m
identifier_name
lib.rs
#![doc(html_root_url = "http://ogeon.github.io/docs/rust-wiringpi/master/")] #![cfg_attr(feature = "strict", deny(warnings))] extern crate libc; use std::marker::PhantomData; use pin::{Pin, Pwm, GpioClock, RequiresRoot}; macro_rules! impl_pins { ($($name:ident),+) => ( $( #[derive(Clone, Copy)] pub struct $name; impl Pin for $name {} )+ ) } macro_rules! impl_pwm { ($($name:ident: $pwm:expr),+) => ( $( impl Pwm for $name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] fn clock_pin() -> ClockPin<$name> { ClockPin::new($pwm) } } )+ ) } macro_rules! require_root { ($($name:ident),+) => ( $( impl RequiresRoot for $name {} )+ ) } mod bindings; pub mod thread { use bindings; use libc; ///This attempts to shift your program (or thread in a multi-threaded ///program) to a higher priority and enables a real-time scheduling. /// ///The priority parameter should be from 0 (the default) to 99 (the ///maximum). This won’t make your program go any faster, but it will give ///it a bigger slice of time when other programs are running. The priority ///parameter works relative to others – so you can make one program ///priority 1 and another priority 2 and it will have the same effect as ///setting one to 10 and the other to 90 (as long as no other programs are ///running with elevated priorities) /// ///The return value is `true` for success and `false` for error. If an ///error is returned, the program should then consult the _errno_ global ///variable, as per the usual conventions. /// ///_Note_: Only programs running as root can change their priority. If ///called from a non-root program then nothing happens. pub fn priority(priority: u8) -> bool { unsafe { bindings::piHiPri(priority as libc::c_int) >= 0 } } } pub mod pin { use bindings; use libc; use self::Value::{Low, High}; use std::marker::PhantomData; const INPUT: libc::c_int = 0; const OUTPUT: libc::c_int = 1; const PWM_OUTPUT: libc::c_int = 2; const GPIO_CLOCK: libc::c_int = 3; //const SOFT_PWM_OUTPUT: libc::c_int = 4; //const SOFT_TONE_OUTPUT: libc::c_int = 5; //const PWM_TONE_OUTPUT: libc::c_int = 6; ///This returns the BCM_GPIO pin number of the supplied **wiringPi** pin. /// ///It takes the board revision into account. pub fn wpi_to_gpio_number(wpi_number: u16) -> u16 { unsafe { bindings::wpiPinToGpio(wpi_number as libc::c_int) as u16 } } ///This returns the BCM_GPIO pin number of the supplied physical pin on ///the P1 connector. pub fn phys_to_gpio_number(phys_number: u16) -> u16 { unsafe { bindings::physPinToGpio(phys_number as libc::c_int) as u16 } } impl_pins!(WiringPi, Gpio, Phys, Sys); impl_pwm!(WiringPi: 1, Gpio: 18, Phys: 12); impl_clock!(WiringPi: 7, Gpio: 4, Phys: 7); require_root!(WiringPi, Gpio, Phys); pub trait Pin {} pub trait Pwm: RequiresRoot + Sized { fn pwm_pin() -> PwmPin<Self>; } pub trait GpioClock: RequiresRoot + Sized { fn clock_pin() -> ClockPin<Self>; } pub trait RequiresRoot: Pin {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Value { Low = 0, High } #[derive(Debug, Clone, Copy)] pub enum Edge { ///No setup is performed, it is assumed the trigger has already been set up previosuly Setup = 0, Falling = 1, Rising = 2, Both = 3 } #[derive(Debug, Clone, Copy)] pub enum Pull { Off = 0, Down, Up } #[derive(Debug, Clone, Copy)] pub enum PwmMode { MarkSpace = 0, Balanced } pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> InputPin<P> { pub fn new(pin: libc::c_int) -> InputPin<P> { unsafe { bindings::pinMode(pin, INPUT); } InputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &InputPin(number, _) = self; number } ///This function returns the value read at the given pin. /// ///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin. pub fn digital_read(&self) -> Value { let value = unsafe { bindings::digitalRead(self.number()) }; if value == 0 { Low } else { High } } ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { bindings::analogRead(self.number()) as u16 } } /// This will register an "Interrupt" to be called when the pin changes state /// Note the quotes around Interrupt, because the current implementation in the C /// library seems to be a dedicated thread that polls the gpio device driver, /// and this callback is called from that thread synchronously, so it's not something that /// you would call a real interrupt in an embedded environement. /// /// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code. /// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for /// ideas on how to work around these limitations if you find them too constraining. /// /// ``` /// use wiringpi; /// /// extern "C" fn change_state() { /// println!("Look ma, I'm being called from an another thread"); /// } /// /// fn main() { /// let pi = wiringpi::setup(); /// let pin = pi.output_pin(0); /// /// pin.register_isr(Edge::Falling, Some(change_state)); /// /// thread::sleep(60000); /// } /// /// ``` /// /// pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) { unsafe { bindings::wiringPiISR(self.number(), edge as i32, f); } } } impl<P: Pin + RequiresRoot> InputPin<P> { ///This sets the pull-up or pull-down resistor mode on the given pin. /// ///Unlike the Arduino, the BCM2835 has both pull-up an down internal ///resistors. The parameter pud should be; `Off`, (no pull up/down), ///`Down` (pull to ground) or `Up` (pull to 3.3v) pub fn pull_up_dn_control(&self, pud: Pull) { unsafe { bindings::pullUpDnControl(self.number(), pud as libc::c_int); } } pub fn into_output(self) -> OutputPin<P> { let InputPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let InputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + Pwm> InputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let InputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> InputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let InputPin(number, _) = self; ClockPin::new(number) } } /// A pin with software controlled PWM output. /// /// Due to limitations of the chip only one pin is able to do /// hardware-controlled PWM output. The `SoftPwmPin`s on the /// other hand allow for all GPIOs to output PWM signals. /// /// The pulse width of the signal will be 100μs with a value range /// of [0,100] \(where `0` is a constant low and `100` is a /// constant high) resulting in a frequenzy of 100 Hz. /// /// **Important**: In order to use software PWM pins *wiringPi* /// has to be setup in GPIO mode via `setup_gpio()`. pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + RequiresRoot> SoftPwmPin<P> { /// Configures the given `pin` to output a software controlled PWM /// signal. pub fn new(pin: libc::c_int) -> SoftPwmPin<P> {
#[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { bindings::softPwmWrite(self.number(), value); } } /// Stops the software handling of this pin. /// /// _Note_: In order to control this pin via software PWM again /// it will need to be recreated using `new()`. pub fn pwm_stop(self) { unsafe { bindings::softPwmStop(self.number()); } } pub fn into_input(self) -> InputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); OutputPin::new(number) } } impl<P: Pin + Pwm> SoftPwmPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); PwmPin::new(number) } } impl<P: Pin + GpioClock> SoftPwmPin<P> { pub fn into_clock(self) -> ClockPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); ClockPin::new(number) } } pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> OutputPin<P> { pub fn new(pin: libc::c_int) -> OutputPin<P> { unsafe { bindings::pinMode(pin, OUTPUT); } OutputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &OutputPin(number, _) = self; number } ///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output. pub fn digital_write(&self, value: Value) { unsafe { bindings::digitalWrite(self.number(), value as libc::c_int); } } ///This writes the given value to the supplied analog pin. You will ///need to register additional analog modules to enable this function ///for devices such as the Gertboard. pub fn analog_write(&self, value: u16) { unsafe { bindings::analogWrite(self.number(), value as libc::c_int); } } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let OutputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_input(self) -> InputPin<P> { let OutputPin(number, _) = self; InputPin::new(number) } } impl<P: Pin + Pwm> OutputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let OutputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> OutputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let OutputPin(number, _) = self; ClockPin::new(number) } } ///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + Pwm> PwmPin<P> { pub fn new(pin: libc::c_int) -> PwmPin<P> { unsafe { bindings::pinMode(pin, PWM_OUTPUT); } PwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &PwmPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let PwmPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let PwmPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let PwmPin(number, _) = self; SoftPwmPin::new(number) } ///Writes the value to the PWM register for the given pin. /// ///The value must be between 0 and 1024. pub fn write(&self, value: u16) { unsafe { bindings::pwmWrite(self.number(), value as libc::c_int); } } ///The PWM generator can run in 2 modes – "balanced" and "mark:space". /// ///The mark:space mode is traditional, however the default mode in the ///Pi is "balanced". You can switch modes by supplying the parameter: ///`Balanced` or `MarkSpace`. pub fn set_mode(&self, mode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as libc::c_uint); } } ///This sets the divisor for the PWM clock. pub fn set_clock(&self, value: u16) { unsafe { bindings::pwmSetClock(value as libc::c_int); } } } pub struct ClockPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + GpioClock> ClockPin<P> { pub fn new(pin: libc::c_int) -> ClockPin<P> { unsafe { bindings::pinMode(pin, GPIO_CLOCK); } ClockPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &ClockPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let ClockPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let ClockPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let ClockPin(number, _) = self; SoftPwmPin::new(number) } ///Set the freuency on a GPIO clock pin. pub fn frequency(&self, freq: u16) { unsafe { bindings::gpioClockSet(self.number(), freq as libc::c_int); } } } } ///This initialises the wiringPi system and assumes that the calling program ///is going to be using the **wiringPi** pin numbering scheme. /// ///This is a simplified numbering scheme which provides a mapping from virtual ///pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. ///See the pins page for a table which maps the **wiringPi** pin number to the ///Broadcom GPIO pin number to the physical location on the edge connector. /// ///This function needs to be called with root privileges. pub fn setup() -> WiringPi<pin::WiringPi> { unsafe { bindings::wiringPiSetup(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the Broadcom GPIO pin numbers directly with no re-mapping. /// ///This function needs to be called with root privileges. pub fn setup_gpio() -> WiringPi<pin::Gpio> { unsafe { bindings::wiringPiSetupGpio(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the physical pin numbers _on the P1 connector only_. /// ///This function needs to be called with root privileges. pub fn setup_phys() -> WiringPi<pin::Phys> { unsafe { bindings::wiringPiSetupPhys(); } WiringPi(PhantomData) } ///This initialises the wiringPi system but uses the /sys/class/gpio interface ///rather than accessing the hardware directly. /// ///This can be called as a non-root user provided the GPIO pins have been ///exported before-hand using the gpio program. Pin number in this mode is the ///native Broadcom GPIO numbers. /// ///_Note_: In this mode you can only use the pins which have been exported via ///the /sys/class/gpio interface. You must export these pins before you call ///your program. You can do this in a separate shell-script, or by using the ///system() function from inside your program. /// ///Also note that some functions have no effect when using this mode as ///they’re not currently possible to action unless called with root ///privileges. pub fn setup_sys() -> WiringPi<pin::Sys> { unsafe { bindings::wiringPiSetupSys(); } WiringPi(PhantomData) } ///This returns the board revision of the Raspberry Pi. /// ///It will be either 1 or 2. Some of the BCM_GPIO pins changed number and ///function when moving from board revision 1 to 2, so if you are using ///BCM_GPIO pin numbers, then you need to be aware of the differences. pub fn board_revision() -> i32 { unsafe { bindings::piBoardRev() } } pub struct WiringPi<Pin>(PhantomData<Pin>); impl<P: Pin> WiringPi<P> { pub fn input_pin(&self, pin: u16) -> pin::InputPin<P> { let pin = pin as libc::c_int; pin::InputPin::new(pin) } pub fn output_pin(&self, pin: u16) -> pin::OutputPin<P> { let pin = pin as libc::c_int; pin::OutputPin::new(pin) } ///This returns a number representing the number if milliseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 49 days. pub fn millis(&self) -> u32 { unsafe { bindings::millis() } } ///This returns a number representing the number if microseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 71 minutes. pub fn micros(&self) -> u32 { unsafe { bindings::micros() } } ///This writes the 8-bit byte supplied to the first 8 GPIO pins. It’s the ///fastest way to set all 8 bits at once to a particular value, although ///it still takes two write operations to the Pi’s GPIO hardware. pub fn digital_write_byte(&self, byte: u8) { unsafe { bindings::digitalWriteByte(byte as libc::c_int); } } } impl<P: Pwm + Pin> WiringPi<P> { pub fn pwm_pin(&self) -> pin::PwmPin<P> { Pwm::pwm_pin() } } impl<P: GpioClock + Pin> WiringPi<P> { pub fn clock_pin(&self) -> pin::ClockPin<P> { GpioClock::clock_pin() } } impl<P: Pin + RequiresRoot> WiringPi<P> { pub fn soft_pwm_pin(&self, pin: u16) -> pin::SoftPwmPin<P> { let pin = pin as libc::c_int; pin::SoftPwmPin::new(pin) } }
unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) }
identifier_body
lib.rs
#![doc(html_root_url = "http://ogeon.github.io/docs/rust-wiringpi/master/")] #![cfg_attr(feature = "strict", deny(warnings))] extern crate libc; use std::marker::PhantomData; use pin::{Pin, Pwm, GpioClock, RequiresRoot}; macro_rules! impl_pins { ($($name:ident),+) => ( $( #[derive(Clone, Copy)] pub struct $name; impl Pin for $name {} )+ ) } macro_rules! impl_pwm { ($($name:ident: $pwm:expr),+) => ( $( impl Pwm for $name { #[inline] fn pwm_pin() -> PwmPin<$name> { PwmPin::new($pwm) } } )+ ) } macro_rules! impl_clock { ($($name:ident: $pwm:expr),+) => ( $( impl GpioClock for $name { #[inline] fn clock_pin() -> ClockPin<$name> { ClockPin::new($pwm) } } )+ ) } macro_rules! require_root { ($($name:ident),+) => ( $( impl RequiresRoot for $name {} )+ ) } mod bindings; pub mod thread { use bindings; use libc; ///This attempts to shift your program (or thread in a multi-threaded ///program) to a higher priority and enables a real-time scheduling. /// ///The priority parameter should be from 0 (the default) to 99 (the ///maximum). This won’t make your program go any faster, but it will give ///it a bigger slice of time when other programs are running. The priority ///parameter works relative to others – so you can make one program ///priority 1 and another priority 2 and it will have the same effect as ///setting one to 10 and the other to 90 (as long as no other programs are ///running with elevated priorities) /// ///The return value is `true` for success and `false` for error. If an ///error is returned, the program should then consult the _errno_ global ///variable, as per the usual conventions. /// ///_Note_: Only programs running as root can change their priority. If ///called from a non-root program then nothing happens. pub fn priority(priority: u8) -> bool { unsafe { bindings::piHiPri(priority as libc::c_int) >= 0 } } } pub mod pin { use bindings; use libc; use self::Value::{Low, High}; use std::marker::PhantomData; const INPUT: libc::c_int = 0; const OUTPUT: libc::c_int = 1; const PWM_OUTPUT: libc::c_int = 2; const GPIO_CLOCK: libc::c_int = 3; //const SOFT_PWM_OUTPUT: libc::c_int = 4; //const SOFT_TONE_OUTPUT: libc::c_int = 5; //const PWM_TONE_OUTPUT: libc::c_int = 6; ///This returns the BCM_GPIO pin number of the supplied **wiringPi** pin. /// ///It takes the board revision into account. pub fn wpi_to_gpio_number(wpi_number: u16) -> u16 { unsafe { bindings::wpiPinToGpio(wpi_number as libc::c_int) as u16 } } ///This returns the BCM_GPIO pin number of the supplied physical pin on ///the P1 connector. pub fn phys_to_gpio_number(phys_number: u16) -> u16 { unsafe { bindings::physPinToGpio(phys_number as libc::c_int) as u16 } } impl_pins!(WiringPi, Gpio, Phys, Sys); impl_pwm!(WiringPi: 1, Gpio: 18, Phys: 12); impl_clock!(WiringPi: 7, Gpio: 4, Phys: 7); require_root!(WiringPi, Gpio, Phys); pub trait Pin {} pub trait Pwm: RequiresRoot + Sized { fn pwm_pin() -> PwmPin<Self>; } pub trait GpioClock: RequiresRoot + Sized { fn clock_pin() -> ClockPin<Self>; } pub trait RequiresRoot: Pin {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Value { Low = 0, High } #[derive(Debug, Clone, Copy)] pub enum Edge { ///No setup is performed, it is assumed the trigger has already been set up previosuly Setup = 0, Falling = 1, Rising = 2, Both = 3 } #[derive(Debug, Clone, Copy)] pub enum Pull { Off = 0, Down, Up } #[derive(Debug, Clone, Copy)] pub enum PwmMode { MarkSpace = 0, Balanced } pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> InputPin<P> { pub fn new(pin: libc::c_int) -> InputPin<P> { unsafe { bindings::pinMode(pin, INPUT); } InputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &InputPin(number, _) = self; number } ///This function returns the value read at the given pin. /// ///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin. pub fn digital_read(&self) -> Value { let value = unsafe { bindings::digitalRead(self.number()) }; if value == 0 { Low } else { High } } ///This returns the value read on the supplied analog input pin. You ///will need to register additional analog modules to enable this ///function for devices such as the Gertboard, quick2Wire analog ///board, etc. pub fn analog_read(&self) -> u16 { unsafe { bindings::analogRead(self.number()) as u16 } } /// This will register an "Interrupt" to be called when the pin changes state /// Note the quotes around Interrupt, because the current implementation in the C /// library seems to be a dedicated thread that polls the gpio device driver, /// and this callback is called from that thread synchronously, so it's not something that /// you would call a real interrupt in an embedded environement. ///
/// /// Unfortunately the C implementation does not allow userdata to be passed around, /// so the callback must be able to determine what caused the interrupt just by the /// function that was invoked. /// /// See https://github.com/Ogeon/rust-wiringpi/pull/28 for /// ideas on how to work around these limitations if you find them too constraining. /// /// ``` /// use wiringpi; /// /// extern "C" fn change_state() { /// println!("Look ma, I'm being called from an another thread"); /// } /// /// fn main() { /// let pi = wiringpi::setup(); /// let pin = pi.output_pin(0); /// /// pin.register_isr(Edge::Falling, Some(change_state)); /// /// thread::sleep(60000); /// } /// /// ``` /// /// pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) { unsafe { bindings::wiringPiISR(self.number(), edge as i32, f); } } } impl<P: Pin + RequiresRoot> InputPin<P> { ///This sets the pull-up or pull-down resistor mode on the given pin. /// ///Unlike the Arduino, the BCM2835 has both pull-up an down internal ///resistors. The parameter pud should be; `Off`, (no pull up/down), ///`Down` (pull to ground) or `Up` (pull to 3.3v) pub fn pull_up_dn_control(&self, pud: Pull) { unsafe { bindings::pullUpDnControl(self.number(), pud as libc::c_int); } } pub fn into_output(self) -> OutputPin<P> { let InputPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let InputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + Pwm> InputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let InputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> InputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let InputPin(number, _) = self; ClockPin::new(number) } } /// A pin with software controlled PWM output. /// /// Due to limitations of the chip only one pin is able to do /// hardware-controlled PWM output. The `SoftPwmPin`s on the /// other hand allow for all GPIOs to output PWM signals. /// /// The pulse width of the signal will be 100μs with a value range /// of [0,100] \(where `0` is a constant low and `100` is a /// constant high) resulting in a frequenzy of 100 Hz. /// /// **Important**: In order to use software PWM pins *wiringPi* /// has to be setup in GPIO mode via `setup_gpio()`. pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + RequiresRoot> SoftPwmPin<P> { /// Configures the given `pin` to output a software controlled PWM /// signal. pub fn new(pin: libc::c_int) -> SoftPwmPin<P> { unsafe { bindings::softPwmCreate(pin, 0, 100); } SoftPwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &SoftPwmPin(number, _) = self; number } /// Sets the duty cycle. /// /// `value` has to be in the interval [0,100]. pub fn pwm_write(&self, value: libc::c_int) { unsafe { bindings::softPwmWrite(self.number(), value); } } /// Stops the software handling of this pin. /// /// _Note_: In order to control this pin via software PWM again /// it will need to be recreated using `new()`. pub fn pwm_stop(self) { unsafe { bindings::softPwmStop(self.number()); } } pub fn into_input(self) -> InputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); OutputPin::new(number) } } impl<P: Pin + Pwm> SoftPwmPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); PwmPin::new(number) } } impl<P: Pin + GpioClock> SoftPwmPin<P> { pub fn into_clock(self) -> ClockPin<P> { let SoftPwmPin(number, _) = self; self.pwm_stop(); ClockPin::new(number) } } pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin> OutputPin<P> { pub fn new(pin: libc::c_int) -> OutputPin<P> { unsafe { bindings::pinMode(pin, OUTPUT); } OutputPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &OutputPin(number, _) = self; number } ///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output. pub fn digital_write(&self, value: Value) { unsafe { bindings::digitalWrite(self.number(), value as libc::c_int); } } ///This writes the given value to the supplied analog pin. You will ///need to register additional analog modules to enable this function ///for devices such as the Gertboard. pub fn analog_write(&self, value: u16) { unsafe { bindings::analogWrite(self.number(), value as libc::c_int); } } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let OutputPin(number, _) = self; SoftPwmPin::new(number) } } impl<P: Pin + RequiresRoot> OutputPin<P> { pub fn into_input(self) -> InputPin<P> { let OutputPin(number, _) = self; InputPin::new(number) } } impl<P: Pin + Pwm> OutputPin<P> { pub fn into_pwm(self) -> PwmPin<P> { let OutputPin(number, _) = self; PwmPin::new(number) } } impl<P: Pin + GpioClock> OutputPin<P> { pub fn into_clock(self) -> ClockPin<P> { let OutputPin(number, _) = self; ClockPin::new(number) } } ///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + Pwm> PwmPin<P> { pub fn new(pin: libc::c_int) -> PwmPin<P> { unsafe { bindings::pinMode(pin, PWM_OUTPUT); } PwmPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &PwmPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let PwmPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let PwmPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let PwmPin(number, _) = self; SoftPwmPin::new(number) } ///Writes the value to the PWM register for the given pin. /// ///The value must be between 0 and 1024. pub fn write(&self, value: u16) { unsafe { bindings::pwmWrite(self.number(), value as libc::c_int); } } ///The PWM generator can run in 2 modes – "balanced" and "mark:space". /// ///The mark:space mode is traditional, however the default mode in the ///Pi is "balanced". You can switch modes by supplying the parameter: ///`Balanced` or `MarkSpace`. pub fn set_mode(&self, mode: PwmMode) { unsafe { bindings::pwmSetMode(mode as libc::c_int); } } ///This sets the range register in the PWM generator. The default is 1024. pub fn set_range(&self, value: u16) { unsafe { bindings::pwmSetRange(value as libc::c_uint); } } ///This sets the divisor for the PWM clock. pub fn set_clock(&self, value: u16) { unsafe { bindings::pwmSetClock(value as libc::c_int); } } } pub struct ClockPin<Pin>(libc::c_int, PhantomData<Pin>); impl<P: Pin + GpioClock> ClockPin<P> { pub fn new(pin: libc::c_int) -> ClockPin<P> { unsafe { bindings::pinMode(pin, GPIO_CLOCK); } ClockPin(pin, PhantomData) } #[inline] pub fn number(&self) -> libc::c_int { let &ClockPin(number, _) = self; number } pub fn into_input(self) -> InputPin<P> { let ClockPin(number, _) = self; InputPin::new(number) } pub fn into_output(self) -> OutputPin<P> { let ClockPin(number, _) = self; OutputPin::new(number) } pub fn into_soft_pwm(self) -> SoftPwmPin<P> { let ClockPin(number, _) = self; SoftPwmPin::new(number) } ///Set the freuency on a GPIO clock pin. pub fn frequency(&self, freq: u16) { unsafe { bindings::gpioClockSet(self.number(), freq as libc::c_int); } } } } ///This initialises the wiringPi system and assumes that the calling program ///is going to be using the **wiringPi** pin numbering scheme. /// ///This is a simplified numbering scheme which provides a mapping from virtual ///pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. ///See the pins page for a table which maps the **wiringPi** pin number to the ///Broadcom GPIO pin number to the physical location on the edge connector. /// ///This function needs to be called with root privileges. pub fn setup() -> WiringPi<pin::WiringPi> { unsafe { bindings::wiringPiSetup(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the Broadcom GPIO pin numbers directly with no re-mapping. /// ///This function needs to be called with root privileges. pub fn setup_gpio() -> WiringPi<pin::Gpio> { unsafe { bindings::wiringPiSetupGpio(); } WiringPi(PhantomData) } ///This is identical to `setup()`, however it allows the calling programs to ///use the physical pin numbers _on the P1 connector only_. /// ///This function needs to be called with root privileges. pub fn setup_phys() -> WiringPi<pin::Phys> { unsafe { bindings::wiringPiSetupPhys(); } WiringPi(PhantomData) } ///This initialises the wiringPi system but uses the /sys/class/gpio interface ///rather than accessing the hardware directly. /// ///This can be called as a non-root user provided the GPIO pins have been ///exported before-hand using the gpio program. Pin number in this mode is the ///native Broadcom GPIO numbers. /// ///_Note_: In this mode you can only use the pins which have been exported via ///the /sys/class/gpio interface. You must export these pins before you call ///your program. You can do this in a separate shell-script, or by using the ///system() function from inside your program. /// ///Also note that some functions have no effect when using this mode as ///they’re not currently possible to action unless called with root ///privileges. pub fn setup_sys() -> WiringPi<pin::Sys> { unsafe { bindings::wiringPiSetupSys(); } WiringPi(PhantomData) } ///This returns the board revision of the Raspberry Pi. /// ///It will be either 1 or 2. Some of the BCM_GPIO pins changed number and ///function when moving from board revision 1 to 2, so if you are using ///BCM_GPIO pin numbers, then you need to be aware of the differences. pub fn board_revision() -> i32 { unsafe { bindings::piBoardRev() } } pub struct WiringPi<Pin>(PhantomData<Pin>); impl<P: Pin> WiringPi<P> { pub fn input_pin(&self, pin: u16) -> pin::InputPin<P> { let pin = pin as libc::c_int; pin::InputPin::new(pin) } pub fn output_pin(&self, pin: u16) -> pin::OutputPin<P> { let pin = pin as libc::c_int; pin::OutputPin::new(pin) } ///This returns a number representing the number if milliseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 49 days. pub fn millis(&self) -> u32 { unsafe { bindings::millis() } } ///This returns a number representing the number if microseconds since ///your program called one of the setup functions. /// ///It returns an unsigned 32-bit number which wraps after 71 minutes. pub fn micros(&self) -> u32 { unsafe { bindings::micros() } } ///This writes the 8-bit byte supplied to the first 8 GPIO pins. It’s the ///fastest way to set all 8 bits at once to a particular value, although ///it still takes two write operations to the Pi’s GPIO hardware. pub fn digital_write_byte(&self, byte: u8) { unsafe { bindings::digitalWriteByte(byte as libc::c_int); } } } impl<P: Pwm + Pin> WiringPi<P> { pub fn pwm_pin(&self) -> pin::PwmPin<P> { Pwm::pwm_pin() } } impl<P: GpioClock + Pin> WiringPi<P> { pub fn clock_pin(&self) -> pin::ClockPin<P> { GpioClock::clock_pin() } } impl<P: Pin + RequiresRoot> WiringPi<P> { pub fn soft_pwm_pin(&self, pin: u16) -> pin::SoftPwmPin<P> { let pin = pin as libc::c_int; pin::SoftPwmPin::new(pin) } }
/// The callback function does not need to be reentrant. /// /// The callback must be an actual function (not a closure!), and must be using /// the extern "C" modifier so that it can be passed to the wiringpi library, /// and called from C code.
random_line_split
utils.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os, sys import scipy.misc as misc import tarfile import zipfile import scipy.io import urllib import cv2 import random # import matplotlib.pyplot as plt # import matplotlib.cm as cm def maybe_download_and_extract(dir_path, model_url, is_zipfile=False, is_tarfile=False): """ Modified implementation from tensorflow/model/cifar10/input_data :param dir_path: :param model_url: :return: """ if not os.path.exists(dir_path): os.makedirs(dir_path) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write( '\r>> Download %s %.1f%%' %(filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() file_path, _ = urllib.urlretrieve(model_url, filepath, reporthook=_progress) print('\n') statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') if is_zipfile: with zipfile.ZipFile(filepath) as zf: # zip_dir = zf.namelist()[0] zf.extractall(dir_path) elif is_tarfile: tarfile.open(file_path, 'r:gz').extractall(dir_path) # def get_vgg19_model_params(dir_path, model_url): def save_image_pre_annotation(pre_annotation, train_image, annotation): pre_annotation = np.array(pre_annotation[0]) pre_annotation = (pre_annotation - np.min(pre_annotation)) \ / (np.max(pre_annotation) - np.min(pre_annotation)) pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0) pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3)) cv2.imshow("generated", pre_annotation) cv2.imshow("image", train_image[0]) cv2.imshow("ground_truth", annotation[0]) def get_model_data(dir_path, model_url): maybe_download_and_extract(dir_path, model_url) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): raise IOError("VGG model params not found") data = scipy.io.loadmat(filepath) return data def xavier_init(inputs, outputs, constant=1): # Xavier initialization low = -constant * np.sqrt(6.0 / (inputs + outputs)) high = constant * np.sqrt(6.0 / (inputs + outputs)) return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32) def get_weights_variable(inputs, outputs, name): w = tf.Variable(xavier_init(inputs, outputs), name=name) return w def get_bias_variable(num, name): b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name) return b def get_variable(weights, name): init = tf.constant_initializer(weights, dtype=tf.float32) var = tf.get_variable(name=name, initializer=init, shape=weights.shape) return var def weights_variable(shape, stddev=0.02, name=None): initial = tf.truncated_normal(shape, stddev=stddev) if name is None: return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial) def bias_variable(shape, name=None): initial = tf.constant(0.0, shape=shape) if name is None: return tf.Variable(initial) else: return tf.get_variable(name=name, initializer=initial) def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2): if output_shape is None: output_shape = x.get_shape().as_list() output_shape[1] *= 2 output_shape[2] *= 2 output_shape[3] *= 2 conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_basic(x, W, b): conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_strided(x, W, b, stride=None, padding='SAME'): if stride is None: conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding) else: conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding) return tf.nn.bias_add(conv, b) def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def process_image(image, mean): return image - mean def add_grad_summary(grad, var): return tf.summary.histogram(var.op.name+'gradient', grad) def save_image(image, save_dir, name, mean=None): """ save the image :param image: :param save_dir: :param name: :param mean: :return: """ if mean: image = unprocess_image(image, mean) misc.imsave(os.path.join(save_dir, name+'.png'), image) def unprocess_image(image, mean): return image+mean def to_categorial(labels): one_hot = np.zeros(labels.shape[0], labels.max() + 1) one_hot[np.array(labels.shape[0], labels)] = 1 return one_hot def compute_euclidean_distance(x, y, positive=True): """ Computes the euclidean distance between two tensorflow variables """ d = tf.square(tf.subtract(x, y)) d = tf.reduce_sum(d, axis=1) if positive: d1, indx = tf.nn.top_k(input=d, k=100) else: d1, indx = tf.nn.top_k(input=-d, k=100) d1 = -1.0 * d1 return d1 * 2.0 def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin): """ Compute the contrastive loss as in L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m **Parameters** anchor_feature: positive_feature: negative_feature: margin: Triplet margin **Returns** Return the loss operation """ with tf.variable_scope('triplet_loss'): pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True) neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False) basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist) def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes): models = [] for i in range(n_classes): indexes = labels_train == i models.append(np.mean(data_train[indexes, :], axis=0)) tp = 0 for i in range(data_validation.shape[0]): d = data_validation[i, :] l = labels_validation[i] scores = [consine(m, d) for m in models] predict = np. argmax(scores) if predict == 1: tp += 1 return (float(tp) / data_validation.shape[0]) * 100 def get_index(labels, val): return [i for i in range(len(labels)) if labels[i] == val] def prewhiten(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) return y def whiten(x): mean = np.mean(x) std = np.std(x) y = np.multiply(np.subtract(x, mean), 1.0 / std) return y def crop(image, random_crop, image_size): if image.shape[1]>image_size:
return image def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image def random_rotate_image(image): angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic') def random_crop(img, image_size): width = height = image_size x = random.randint(0, img.shape[1] - width) y = random.randint(0, img.shape[0] - height) return img[y:y+height, x:x+width] def get_center_loss(features, labels, alpha, num_classes): """获取center loss及center的更新op Arguments: features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length]. labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size]. alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文. num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少. Return: loss: Tensor,可与softmax loss相加作为总的loss进行优化. centers: Tensor,存储样本中心值的Tensor,仅查看样本中心存储的具体数值时有用. centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新 """ # 获取特征的维数,例如256维 len_features = features.get_shape()[1] # 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心, # 设置trainable=False是因为样本中心不是由梯度进行更新的 centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) # 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要 labels = tf.reshape(labels, [-1]) # 根据样本label,获取mini-batch中每一个样本对应的中心值 centers_batch = tf.gather(centers, labels) # 计算loss loss = tf.reduce_mean(tf.square(features - centers_batch)) # 当前mini-batch的特征值与它们对应的中心值之间的差 diff = centers_batch - features # 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4) unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff = diff / tf.cast((1 + appear_times), tf.float32) diff = alpha * diff centers_update_op = tf.scatter_sub(centers, labels, diff) return loss, centers, centers_update_op # def plot_embedding(X, y, title=None): # x_min, x_max = bp.min(X, 0), np.max(X, 0) # X = (X - x_min) / (x_max - x_min) # # plt.figure(figsize=(10, 10)) # ax = plt.subplot(111) # for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(y[i]), color=cm.Set1(y[i] / 10.0), fontdict={'weight': 'bold', 'size': 9}) # # plt.xticks([]), plt.yticks([]) # if title is not None: # plt.title(title)
sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) = (0, 0) image = image[(sz1-sz2+v):(sz1+sz2+v + 1), (sz1-sz2+h):(sz1+sz2+h + 1), :]
conditional_block
utils.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os, sys import scipy.misc as misc import tarfile import zipfile import scipy.io import urllib import cv2 import random # import matplotlib.pyplot as plt # import matplotlib.cm as cm def maybe_download_and_extract(dir_path, model_url, is_zipfile=False, is_tarfile=False): """ Modified implementation from tensorflow/model/cifar10/input_data :param dir_path: :param model_url: :return: """ if not os.path.exists(dir_path): os.makedirs(dir_path) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write( '\r>> Download %s %.1f%%' %(filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() file_path, _ = urllib.urlretrieve(model_url, filepath, reporthook=_progress) print('\n') statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') if is_zipfile: with zipfile.ZipFile(filepath) as zf: # zip_dir = zf.namelist()[0] zf.extractall(dir_path) elif is_tarfile: tarfile.open(file_path, 'r:gz').extractall(dir_path) # def get_vgg19_model_params(dir_path, model_url): def save_image_pre_annotation(pre_annotation, train_image, annotation): pre_annotation = np.array(pre_annotation[0]) pre_annotation = (pre_annotation - np.min(pre_annotation)) \ / (np.max(pre_annotation) - np.min(pre_annotation)) pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0) pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3)) cv2.imshow("generated", pre_annotation) cv2.imshow("image", train_image[0]) cv2.imshow("ground_truth", annotation[0]) def get_model_data(dir_path, model_url): maybe_download_and_extract(dir_path, model_url) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): raise IOError("VGG model params not found") data = scipy.io.loadmat(filepath) return data def xavier_init(inputs, outputs, constant=1): # Xavier initialization low = -constant * np.sqrt(6.0 / (inputs + outputs)) high = constant * np.sqrt(6.0 / (inputs + outputs)) return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32) def get_weights_variable(inputs, outputs, name): w = tf.Variable(xavier_init(inputs, outputs), name=name) return w def get_bias_variable(num, name): b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name) return b def get_variable(weights, name): init = tf.constant_initializer(weights, dtype=tf.float32) var = tf.get_variable(name=name, initializer=init, shape=weights.shape) return var def weights_variable(shape, stddev=0.02, name=None): initial = tf.truncated_normal(shape, stddev=stddev) if name is None: return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial) def bias_variable(shape, name=None): initial = tf.constant(0.0, shape=shape) if name is None: return tf.Variable(initial) else: return tf.get_variable(name=name, initializer=initial) def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2): if output_shape is None: output_shape = x.get_shape().as_list() output_shape[1] *= 2 output_shape[2] *= 2 output_shape[3] *= 2 conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_basic(x, W, b): conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_strided(x, W, b, stride=None, padding='SAME'): if stride is None: conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding) else: conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding) return tf.nn.bias_add(conv, b) def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def process_image(image, mean): return image - mean def add_grad_summary(grad, var): return tf.summary.histogram(var.op.name+'gradient', grad) def save_image(image, save_dir, name, mean=None): """ save the image :param image: :param save_dir: :param name: :param mean: :return: """ if mean: image = unprocess_image(image, mean) misc.imsave(os.path.join(save_dir, name+'.png'), image) def unprocess_image(image, mean): return image+mean def to_categorial(labels): one_hot = np.zeros(labels.shape[0], labels.max() + 1) one_hot[np.array(labels.shape[0], labels)] = 1 return one_hot def compute_euclidean_distance(x, y, positive=True): """ Computes the euclidean distance between two tensorflow variables """ d = tf.square(tf.subtract(x, y)) d = tf.reduce_sum(d, axis=1) if positive: d1, indx = tf.nn.top_k(input=d, k=100) else: d1, indx = tf.nn.top_k(input=-d, k=100) d1 = -1.0 * d1 return d1 * 2.0 def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin): """ Compute the contrastive loss as in L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m **Parameters** anchor_feature: positive_feature: negative_feature: margin: Triplet margin **Returns** Return the loss operation """ with tf.variable_scope('triplet_loss'): pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True) neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False) basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist) def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes): models = [] for i in range(n_classes): indexes = labels_train == i models.append(np.mean(data_train[indexes, :], axis=0)) tp = 0 for i in range(data_validation.shape[0]): d = data_validation[i, :] l = labels_validation[i] scores = [consine(m, d) for m in models] predict = np. argmax(scores) if predict == 1: tp += 1 return (float(tp) / data_validation.shape[0]) * 100 def get_index(labels, val): return [i for i in range(len(labels)) if labels[i] == val] def prewhiten(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) return y def whiten(x): mean = np.mean(x) std = np.std(x) y = np.multiply(np.subtract(x, mean), 1.0 / std) return y def crop(image, random_crop, image_size): if image.shape[1]>image_size: sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) = (0, 0) image = image[(sz1-sz2+v):(sz1+sz2+v + 1), (sz1-sz2+h):(sz1+sz2+h + 1), :] return image def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image def random_rotate_image(image): angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic')
return img[y:y+height, x:x+width] def get_center_loss(features, labels, alpha, num_classes): """获取center loss及center的更新op Arguments: features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length]. labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size]. alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文. num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少. Return: loss: Tensor,可与softmax loss相加作为总的loss进行优化. centers: Tensor,存储样本中心值的Tensor,仅查看样本中心存储的具体数值时有用. centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新 """ # 获取特征的维数,例如256维 len_features = features.get_shape()[1] # 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心, # 设置trainable=False是因为样本中心不是由梯度进行更新的 centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) # 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要 labels = tf.reshape(labels, [-1]) # 根据样本label,获取mini-batch中每一个样本对应的中心值 centers_batch = tf.gather(centers, labels) # 计算loss loss = tf.reduce_mean(tf.square(features - centers_batch)) # 当前mini-batch的特征值与它们对应的中心值之间的差 diff = centers_batch - features # 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4) unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff = diff / tf.cast((1 + appear_times), tf.float32) diff = alpha * diff centers_update_op = tf.scatter_sub(centers, labels, diff) return loss, centers, centers_update_op # def plot_embedding(X, y, title=None): # x_min, x_max = bp.min(X, 0), np.max(X, 0) # X = (X - x_min) / (x_max - x_min) # # plt.figure(figsize=(10, 10)) # ax = plt.subplot(111) # for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(y[i]), color=cm.Set1(y[i] / 10.0), fontdict={'weight': 'bold', 'size': 9}) # # plt.xticks([]), plt.yticks([]) # if title is not None: # plt.title(title)
def random_crop(img, image_size): width = height = image_size x = random.randint(0, img.shape[1] - width) y = random.randint(0, img.shape[0] - height)
random_line_split
utils.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os, sys import scipy.misc as misc import tarfile import zipfile import scipy.io import urllib import cv2 import random # import matplotlib.pyplot as plt # import matplotlib.cm as cm def maybe_download_and_extract(dir_path, model_url, is_zipfile=False, is_tarfile=False): """ Modified implementation from tensorflow/model/cifar10/input_data :param dir_path: :param model_url: :return: """ if not os.path.exists(dir_path): os.makedirs(dir_path) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write( '\r>> Download %s %.1f%%' %(filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() file_path, _ = urllib.urlretrieve(model_url, filepath, reporthook=_progress) print('\n') statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') if is_zipfile: with zipfile.ZipFile(filepath) as zf: # zip_dir = zf.namelist()[0] zf.extractall(dir_path) elif is_tarfile: tarfile.open(file_path, 'r:gz').extractall(dir_path) # def get_vgg19_model_params(dir_path, model_url): def save_image_pre_annotation(pre_annotation, train_image, annotation): pre_annotation = np.array(pre_annotation[0]) pre_annotation = (pre_annotation - np.min(pre_annotation)) \ / (np.max(pre_annotation) - np.min(pre_annotation)) pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0) pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3)) cv2.imshow("generated", pre_annotation) cv2.imshow("image", train_image[0]) cv2.imshow("ground_truth", annotation[0]) def get_model_data(dir_path, model_url): maybe_download_and_extract(dir_path, model_url) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): raise IOError("VGG model params not found") data = scipy.io.loadmat(filepath) return data def xavier_init(inputs, outputs, constant=1): # Xavier initialization low = -constant * np.sqrt(6.0 / (inputs + outputs)) high = constant * np.sqrt(6.0 / (inputs + outputs)) return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32) def get_weights_variable(inputs, outputs, name): w = tf.Variable(xavier_init(inputs, outputs), name=name) return w def get_bias_variable(num, name): b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name) return b def get_variable(weights, name): init = tf.constant_initializer(weights, dtype=tf.float32) var = tf.get_variable(name=name, initializer=init, shape=weights.shape) return var def weights_variable(shape, stddev=0.02, name=None): initial = tf.truncated_normal(shape, stddev=stddev) if name is None: return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial) def bias_variable(shape, name=None): initial = tf.constant(0.0, shape=shape) if name is None: return tf.Variable(initial) else: return tf.get_variable(name=name, initializer=initial) def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2): if output_shape is None: output_shape = x.get_shape().as_list() output_shape[1] *= 2 output_shape[2] *= 2 output_shape[3] *= 2 conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_basic(x, W, b): conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_strided(x, W, b, stride=None, padding='SAME'): if stride is None: conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding) else: conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding) return tf.nn.bias_add(conv, b) def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def process_image(image, mean): return image - mean def add_grad_summary(grad, var): return tf.summary.histogram(var.op.name+'gradient', grad) def save_image(image, save_dir, name, mean=None): """ save the image :param image: :param save_dir: :param name: :param mean: :return: """ if mean: image = unprocess_image(image, mean) misc.imsave(os.path.join(save_dir, name+'.png'), image) def
(image, mean): return image+mean def to_categorial(labels): one_hot = np.zeros(labels.shape[0], labels.max() + 1) one_hot[np.array(labels.shape[0], labels)] = 1 return one_hot def compute_euclidean_distance(x, y, positive=True): """ Computes the euclidean distance between two tensorflow variables """ d = tf.square(tf.subtract(x, y)) d = tf.reduce_sum(d, axis=1) if positive: d1, indx = tf.nn.top_k(input=d, k=100) else: d1, indx = tf.nn.top_k(input=-d, k=100) d1 = -1.0 * d1 return d1 * 2.0 def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin): """ Compute the contrastive loss as in L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m **Parameters** anchor_feature: positive_feature: negative_feature: margin: Triplet margin **Returns** Return the loss operation """ with tf.variable_scope('triplet_loss'): pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True) neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False) basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist) def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes): models = [] for i in range(n_classes): indexes = labels_train == i models.append(np.mean(data_train[indexes, :], axis=0)) tp = 0 for i in range(data_validation.shape[0]): d = data_validation[i, :] l = labels_validation[i] scores = [consine(m, d) for m in models] predict = np. argmax(scores) if predict == 1: tp += 1 return (float(tp) / data_validation.shape[0]) * 100 def get_index(labels, val): return [i for i in range(len(labels)) if labels[i] == val] def prewhiten(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) return y def whiten(x): mean = np.mean(x) std = np.std(x) y = np.multiply(np.subtract(x, mean), 1.0 / std) return y def crop(image, random_crop, image_size): if image.shape[1]>image_size: sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) = (0, 0) image = image[(sz1-sz2+v):(sz1+sz2+v + 1), (sz1-sz2+h):(sz1+sz2+h + 1), :] return image def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image def random_rotate_image(image): angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic') def random_crop(img, image_size): width = height = image_size x = random.randint(0, img.shape[1] - width) y = random.randint(0, img.shape[0] - height) return img[y:y+height, x:x+width] def get_center_loss(features, labels, alpha, num_classes): """获取center loss及center的更新op Arguments: features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length]. labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size]. alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文. num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少. Return: loss: Tensor,可与softmax loss相加作为总的loss进行优化. centers: Tensor,存储样本中心值的Tensor,仅查看样本中心存储的具体数值时有用. centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新 """ # 获取特征的维数,例如256维 len_features = features.get_shape()[1] # 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心, # 设置trainable=False是因为样本中心不是由梯度进行更新的 centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) # 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要 labels = tf.reshape(labels, [-1]) # 根据样本label,获取mini-batch中每一个样本对应的中心值 centers_batch = tf.gather(centers, labels) # 计算loss loss = tf.reduce_mean(tf.square(features - centers_batch)) # 当前mini-batch的特征值与它们对应的中心值之间的差 diff = centers_batch - features # 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4) unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff = diff / tf.cast((1 + appear_times), tf.float32) diff = alpha * diff centers_update_op = tf.scatter_sub(centers, labels, diff) return loss, centers, centers_update_op # def plot_embedding(X, y, title=None): # x_min, x_max = bp.min(X, 0), np.max(X, 0) # X = (X - x_min) / (x_max - x_min) # # plt.figure(figsize=(10, 10)) # ax = plt.subplot(111) # for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(y[i]), color=cm.Set1(y[i] / 10.0), fontdict={'weight': 'bold', 'size': 9}) # # plt.xticks([]), plt.yticks([]) # if title is not None: # plt.title(title)
unprocess_image
identifier_name
utils.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os, sys import scipy.misc as misc import tarfile import zipfile import scipy.io import urllib import cv2 import random # import matplotlib.pyplot as plt # import matplotlib.cm as cm def maybe_download_and_extract(dir_path, model_url, is_zipfile=False, is_tarfile=False): """ Modified implementation from tensorflow/model/cifar10/input_data :param dir_path: :param model_url: :return: """ if not os.path.exists(dir_path): os.makedirs(dir_path) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): def _progress(count, block_size, total_size): sys.stdout.write( '\r>> Download %s %.1f%%' %(filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() file_path, _ = urllib.urlretrieve(model_url, filepath, reporthook=_progress) print('\n') statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') if is_zipfile: with zipfile.ZipFile(filepath) as zf: # zip_dir = zf.namelist()[0] zf.extractall(dir_path) elif is_tarfile: tarfile.open(file_path, 'r:gz').extractall(dir_path) # def get_vgg19_model_params(dir_path, model_url): def save_image_pre_annotation(pre_annotation, train_image, annotation): pre_annotation = np.array(pre_annotation[0]) pre_annotation = (pre_annotation - np.min(pre_annotation)) \ / (np.max(pre_annotation) - np.min(pre_annotation)) pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0) pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3)) cv2.imshow("generated", pre_annotation) cv2.imshow("image", train_image[0]) cv2.imshow("ground_truth", annotation[0]) def get_model_data(dir_path, model_url): maybe_download_and_extract(dir_path, model_url) filename = model_url.split('/')[-1] filepath = os.path.join(dir_path, filename) if not os.path.exists(filepath): raise IOError("VGG model params not found") data = scipy.io.loadmat(filepath) return data def xavier_init(inputs, outputs, constant=1): # Xavier initialization low = -constant * np.sqrt(6.0 / (inputs + outputs)) high = constant * np.sqrt(6.0 / (inputs + outputs)) return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32) def get_weights_variable(inputs, outputs, name): w = tf.Variable(xavier_init(inputs, outputs), name=name) return w def get_bias_variable(num, name):
def get_variable(weights, name): init = tf.constant_initializer(weights, dtype=tf.float32) var = tf.get_variable(name=name, initializer=init, shape=weights.shape) return var def weights_variable(shape, stddev=0.02, name=None): initial = tf.truncated_normal(shape, stddev=stddev) if name is None: return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial) def bias_variable(shape, name=None): initial = tf.constant(0.0, shape=shape) if name is None: return tf.Variable(initial) else: return tf.get_variable(name=name, initializer=initial) def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2): if output_shape is None: output_shape = x.get_shape().as_list() output_shape[1] *= 2 output_shape[2] *= 2 output_shape[3] *= 2 conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_basic(x, W, b): conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.bias_add(conv, b) def conv2d_strided(x, W, b, stride=None, padding='SAME'): if stride is None: conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding) else: conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding) return tf.nn.bias_add(conv, b) def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def process_image(image, mean): return image - mean def add_grad_summary(grad, var): return tf.summary.histogram(var.op.name+'gradient', grad) def save_image(image, save_dir, name, mean=None): """ save the image :param image: :param save_dir: :param name: :param mean: :return: """ if mean: image = unprocess_image(image, mean) misc.imsave(os.path.join(save_dir, name+'.png'), image) def unprocess_image(image, mean): return image+mean def to_categorial(labels): one_hot = np.zeros(labels.shape[0], labels.max() + 1) one_hot[np.array(labels.shape[0], labels)] = 1 return one_hot def compute_euclidean_distance(x, y, positive=True): """ Computes the euclidean distance between two tensorflow variables """ d = tf.square(tf.subtract(x, y)) d = tf.reduce_sum(d, axis=1) if positive: d1, indx = tf.nn.top_k(input=d, k=100) else: d1, indx = tf.nn.top_k(input=-d, k=100) d1 = -1.0 * d1 return d1 * 2.0 def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin): """ Compute the contrastive loss as in L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m **Parameters** anchor_feature: positive_feature: negative_feature: margin: Triplet margin **Returns** Return the loss operation """ with tf.variable_scope('triplet_loss'): pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True) neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False) basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin) loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0) return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist) def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes): models = [] for i in range(n_classes): indexes = labels_train == i models.append(np.mean(data_train[indexes, :], axis=0)) tp = 0 for i in range(data_validation.shape[0]): d = data_validation[i, :] l = labels_validation[i] scores = [consine(m, d) for m in models] predict = np. argmax(scores) if predict == 1: tp += 1 return (float(tp) / data_validation.shape[0]) * 100 def get_index(labels, val): return [i for i in range(len(labels)) if labels[i] == val] def prewhiten(x): mean = np.mean(x) std = np.std(x) std_adj = np.maximum(std, 1.0/np.sqrt(x.size)) y = np.multiply(np.subtract(x, mean), 1/std_adj) return y def whiten(x): mean = np.mean(x) std = np.std(x) y = np.multiply(np.subtract(x, mean), 1.0 / std) return y def crop(image, random_crop, image_size): if image.shape[1]>image_size: sz1 = int(image.shape[1]//2) sz2 = int(image_size//2) if random_crop: diff = sz1-sz2 (h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1)) else: (h, v) = (0, 0) image = image[(sz1-sz2+v):(sz1+sz2+v + 1), (sz1-sz2+h):(sz1+sz2+h + 1), :] return image def flip(image, random_flip): if random_flip and np.random.choice([True, False]): image = np.fliplr(image) return image def random_rotate_image(image): angle = np.random.uniform(low=-10.0, high=10.0) return misc.imrotate(image, angle, 'bicubic') def random_crop(img, image_size): width = height = image_size x = random.randint(0, img.shape[1] - width) y = random.randint(0, img.shape[0] - height) return img[y:y+height, x:x+width] def get_center_loss(features, labels, alpha, num_classes): """获取center loss及center的更新op Arguments: features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length]. labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size]. alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文. num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少. Return: loss: Tensor,可与softmax loss相加作为总的loss进行优化. centers: Tensor,存储样本中心值的Tensor,仅查看样本中心存储的具体数值时有用. centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新 """ # 获取特征的维数,例如256维 len_features = features.get_shape()[1] # 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心, # 设置trainable=False是因为样本中心不是由梯度进行更新的 centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) # 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要 labels = tf.reshape(labels, [-1]) # 根据样本label,获取mini-batch中每一个样本对应的中心值 centers_batch = tf.gather(centers, labels) # 计算loss loss = tf.reduce_mean(tf.square(features - centers_batch)) # 当前mini-batch的特征值与它们对应的中心值之间的差 diff = centers_batch - features # 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4) unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff = diff / tf.cast((1 + appear_times), tf.float32) diff = alpha * diff centers_update_op = tf.scatter_sub(centers, labels, diff) return loss, centers, centers_update_op # def plot_embedding(X, y, title=None): # x_min, x_max = bp.min(X, 0), np.max(X, 0) # X = (X - x_min) / (x_max - x_min) # # plt.figure(figsize=(10, 10)) # ax = plt.subplot(111) # for i in range(X.shape[0]): # plt.text(X[i, 0], X[i, 1], str(y[i]), color=cm.Set1(y[i] / 10.0), fontdict={'weight': 'bold', 'size': 9}) # # plt.xticks([]), plt.yticks([]) # if title is not None: # plt.title(title)
b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name) return b
identifier_body
bloom-atlas.js
(function(_BA) { 'use strict'; var Atlas, checkCookie, extend, gbi, getAllElementsWithAttribute, gvi, loaded, random, setCookie, uuid, wrapOnload; loaded = false; wrapOnload = function(fn, context) { var combined, current; if (loaded) { return fn(); } if (window.attachEvent) { return window.attachEvent('onload', function() { loaded = true; if (!context) { return fn(); } return fn.call(context); }); } else { if (window.onload) { current = window.onload; combined = function() { loaded = true; current(); if (!context) { return fn(); } return fn.call(context); }; return window.onload = combined; } else { return window.onload = function() { loaded = true; if (!context) { return fn(); } return fn.call(context); }; } } }; extend = function(one, two) { var k, _i, _len, _ref; if (!one && !two) { return {}; } if (!two || typeof two !== 'object') { return one; } if (!one || typeof one !== 'object') { return two; } _ref = Object.keys(two); for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; one[k] = two[k]; } return one; }; getAllElementsWithAttribute = function(attr) { var all, el, matching, _i, _len; matching = []; all = document.getElementsByTagName('*'); for (_i = 0, _len = all.length; _i < _len; _i++) { el = all[_i]; if (el.getAttribute(attr)) { matching.push(el); } } return matching; }; uuid = function() { var d; d = Date.now(); return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { var r; r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : r & 0x7 | 0x8).toString(16); }); }; random = function(l) { var i, list, token; l = l || 10; token = ""; list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; i = 0; while (i < l) { token += list.charAt(Math.floor(Math.random() * list.length)); i++; } return token; }; checkCookie = function(name) { var end, start, val; val = document.cookie; start = val.indexOf(" " + name + "="); if (start === -1) { start = val.indexOf(name + "="); } if (start === -1) { val = null; } else { start = val.indexOf("=", start) + 1; end = val.indexOf(";", start); if (end === -1) { end = val.length; } val = unescape(val.substring(start, end)); } return ((val != null) && val !== "null" && val !== "" ? val : null); }; setCookie = function(name, val, minutes) { var expires; expires = new Date(); expires.setMinutes(expires.getMinutes() + minutes); document.cookie = name + '=' + val + '; expires=' + expires.toUTCString() + '; path=/;'; return val; }; gbi = function(data) { var M, N, r, tem, ua; data = data || {}; N = navigator.appName; ua = navigator.userAgent; tem = void 0; r = /(crios|opera|chrome|safari|firefox|msie|android|iphone|ipad)\/?\s*(\.?\d+(\.\d+)*)/i; M = ua.match(r); if (M && ((tem = ua.match(/version\/([\.\d]+)/i)) != null)) { M[2] = tem[1]; } data.b = M[1]; data.bv = M[2]; data.sw = screen.width; data.sh = screen.height; data.bw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0; data.bh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0; r = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i; if (r.test(navigator.userAgent)) { data.bm = true; } else { data.bm = false; } if (navigator.appVersion.indexOf("Win") !== -1) { data.os = "Windows"; } else if (navigator.appVersion.indexOf("iPad") !== -1) { data.os = "iOS"; } else if (navigator.appVersion.indexOf("iPhone") !== -1) { data.os = "iOS"; } else if (navigator.appVersion.indexOf("Android") !== -1) { data.os = "Android"; } else if (navigator.appVersion.indexOf("Mac") !== -1) { data.os = "Mac"; } else if (navigator.appVersion.indexOf("Linux") !== -1) { data.os = "Linux"; } else if (navigator.appVersion.indexOf("X11") !== -1) { data.os = "Unix"; } else { data.os = "Unknown"; } return data; }; gvi = function(data) { var rf, rh, _t; data = data || {}; _t = new Date(); data.tl = new Date(); _t = _t.toString(); data.tz = (_t.indexOf("(") > -1 ? _t.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join("") : _t.match(/[A-Z]{3,4}/)[0]); if (_BA._tz === "GMT" && /(GMT\W*\d{4})/.test(_t)) { data.tz = RegExp.$1; } data.h = window.location.host; data.hf = window.location.href; rh = document.referrer.split("/")[2]; if (rh) { data.rh = rh; } rf = document.referrer; if (rf) { data.rf = rf; } return data; }; /* # translations data = c: (if typeof params.c isnt 'undefined' then params.c else null) # campaign s: (if typeof params.s isnt 'undefined' then params.s else null) # secret cs: [] # secondary campaigns bz: [] # bloom zones be: [] # bloom event listeners BIRD: null # Bloom Internal Referral Data vt: null # visitor token (long term) st: null # session token (short term) it: null # impression token (unique) rv: false # returning visitor tz: null # time zone tl: null # time local sw: null # screen width sh: null # screen height bw: null # browser width bh: null # browser height b: null # browser bv: null # browser version bm: false # browser mobile os: null # operating system h: null # host hf: null # host full rh: null # referrer host rf: null # referrer full */ Atlas = function(params) { var e; if (!(this instanceof Atlas)) { return new Atlas(params); } this.useBIRD = (typeof params.BIRD !== 'undefined' ? params.BIRD : false); this.c = (typeof params.c !== 'undefined' ? params.c : null); this.it = null; if (!this.c) { e = 'Atlas could not instantiate - no campaign specified!'; throw new Error(e); } wrapOnload(this.initBells, this); this.capture(); return this; }; Atlas.prototype.reload = function(c) { this.c = c || this.c || uuid(); wrapOnload(this.initBells, this); wrapOnload(this.initGazelle, this); return this.capture(); }; Atlas.prototype.initBells = function() { var bell, bells, e, _i, _len, _results, _this = this; bells = getAllElementsWithAttribute('data-BELL'); console.log('Got bells.', bells); e = 'click'; _results = []; for (_i = 0, _len = bells.length; _i < _len; _i++) { bell = bells[_i]; _results.push((function(bell) { var campaign, cb; campaign = bell.getAttribute('data-BELL'); cb = function() { console.log('Someone rang the bell.', campaign); _this.save({ c: campaign }, 'event'); return bell.removeEventListener(e, cb); }; bell.addEventListener(e, cb); return bell.removeAttribute('data-BELL'); })(bell)); } return _results; }; Atlas.prototype.initGazelle = function() { var p, placeholders, requests, _fn, _i, _len; placeholders = getAllElementsWithAttribute('data-GAZELLE'); requests = []; _fn = function(p) { var data, e, r; data = p.getAttribute('data-GAZELLE'); try { r = JSON.parse(data); return requests.push(r); } catch (_error) { e = _error; throw new Error('Error! Badly formatted Gazelle parameters.'); } }; for (_i = 0, _len = placeholders.length; _i < _len; _i++) { p = placeholders[_i]; _fn(p); } return console.log('Initialized requests.', requests); }; Atlas.prototype.BIRD = function() { var anchors, data, hash, hashes, href, i, useBIRD; data = data || {}; data.BIRD = null; useBIRD = this.useBIRD || false; hashes = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&"); i = 0; while (i < hashes.length) { hash = hashes[i].split("="); if (hash[0] === "BIRD") {
return data; } else { data.BIRD = hash[1]; break; } } i++; } anchors = document.getElementsByTagName('a'); href = ''; i = 0; while (i < anchors.length) { href = anchors[i].getAttribute("href"); if (href !== "#") { href += (href.indexOf("?") !== 0 ? "&" : "?"); href += "BIRD=" + _BA._c; anchors[i].setAttribute("href", href); } i++; } console.log('got BIRD.', data.BIRD); return data; }; Atlas.prototype.capture = function(data) { data = data || {}; data = extend(data, gbi()); data = extend(data, gvi()); data = extend(data, this.BIRD()); data.it = this.it = uuid(); data.c = data.c || this.c; this.save(data, 'impression'); return this; }; Atlas.prototype.save = function(data, type) { var img, src, _this = this; data.vt = (function() { var val; val = checkCookie('_BA_vt'); if (val && type === 'impression') { data.rv = true; } return val; })() || (function() { data.rv = false; return setCookie('_BA_vt', uuid(), 60 * 24 * 365 * 2); })(); data.st = checkCookie('_BA_st'); data.st = setCookie('_BA_st', data.st || uuid(), 30); data.it = this.it || (function() { _this.it = uuid(); return _this.it; }); type = type || 'meta'; if (type !== 'impression' && type !== 'event' && type !== 'meta') { type = 'meta'; } data.type = type; img = new Image(); src = 'http://localhost:1337/bat.gif?'; console.log('Sending data.', data); src += 'data=' + encodeURIComponent(JSON.stringify(data)); src += '&'; src += Date.now(); img.src = src; console.log('Created image src.', src); return this; }; return window.Atlas = new Atlas(_BA); })(window._BA || {});
if (useBIRD === false) { data.BIRD = hash[1];
random_line_split
QTofflineTemplate.py
from pyqtgraph.Qt import QtGui, QtCore from sklearn import preprocessing import numpy as np import pyqtgraph as pg import random import pickle import collections from os import listdir from os.path import isfile, join import fastdtw from scipy.spatial.distance import euclidean import scipy.stats from scipy import signal import DTW import time import matplotlib.pyplot as plt import pickle from scipy import signal from numpy.fft import fft, ifft, fft2, ifft2, fftshift from scipy import stats import re DirSetting ='./Jay/' #base gesture Dit ComplexDirSetting ='./Jay/Complex/' #complex gesture Dir Name = 'Jay' #the prefix of filename ''' MyRealTimePlot: create UI and construct the DTW Model setMyData : a real-time ploter DrawPic : draw the specificed file data compare : compare two specificed file data by DTW and return the Distance JudgeAll : Recognize all the file include base gesture and complex gesture. This function is for getting accuracy for test set. *** If you need GUI only, you do not need this function *** ''' def absDist(A,B): return np.sum(np.abs(A-B)) class
(): def __init__(self,dataSource = None,nameList=['Plot1','Plot2','Plot3','Plot4','Plot5','Plot6']): ''' construct GUI ''' self.numOfDataToPlot = 500 #nuber of point of x self.ScalerNum = 2 # every self.ScalerNum we sample once - not used self.numofPlotWidget=3 self.plotNum = 3 # how many line to plot in a plot widget self.plotWidgetList = [] self.penStyleList= [[(0,0,200),(200,200,100),(195,46,212)],[(237,177,32),(126,47,142),(43,128,200)],[(0,0,200),(200,200,100),(195,46,212)]] self.index=0 self.dataListLen = [] self.ROI1 = None # region of interest self.ROI2 = None self.dataTotolLen = 0 self.curveList = [] self.curveList2 = [] self.curveXData =[i for i in range(0,self.numOfDataToPlot) ] #initial x value self.curveYDataList=[] self.curveYDataList2=[] self.app = QtGui.QApplication([]) self.mainWindow = QtGui.QMainWindow() self.mainWindow.setWindowTitle('pyqtgraph example: PlotWidget') self.mainWindow.resize(720,640) self.GuiWiget = QtGui.QWidget() self.mainWindow.setCentralWidget(self.GuiWiget) layout = QtGui.QVBoxLayout() secondLayout = QtGui.QHBoxLayout() thirdLayout = QtGui.QHBoxLayout() self.GuiWiget.setLayout(layout) layout.addLayout(secondLayout) layout.addLayout(thirdLayout) pg.setConfigOption('background', 'w') # create plot widgets by pg.PlotWidget(name=name) and we can draw multiple curve lines on it for i,name in zip(range(0,self.numofPlotWidget),nameList): plotWidget = pg.PlotWidget(name=name) # set X range plotWidget.setXRange(0, self.numOfDataToPlot) # set Y range if i == 0 : plotWidget.setYRange(-2, 2) elif i == 1: plotWidget.setYRange(-180, 180) else: plotWidget.setYRange(-2, 2) layout.addWidget(plotWidget) self.plotWidgetList.append(plotWidget) self.startLabel= QtGui.QLabel("Start:") self.startWindows = QtGui.QLineEdit() self.endLabel= QtGui.QLabel("End:") self.endWindows = QtGui.QLineEdit() self.button = QtGui.QPushButton('Split') self.button.clicked.connect(self.DrawPic) self.fileName= QtGui.QLabel("fileName:") self.fileInputName = QtGui.QComboBox() #self.fileInputName.setText("UpStraight0.dat") self.Readbutton = QtGui.QPushButton('Read') self.Readbutton.clicked.connect(self.ReadFile) secondLayout.addWidget(self.startLabel) secondLayout.addWidget(self.startWindows) secondLayout.addWidget(self.endLabel) secondLayout.addWidget(self.endWindows) secondLayout.addWidget(self.button) secondLayout.addWidget(self.fileName) secondLayout.addWidget(self.fileInputName) secondLayout.addWidget(self.Readbutton) self.Aobj= QtGui.QLabel("A:") self.comboA = QtGui.QComboBox() self.AstartLabel= QtGui.QLabel("Start:") self.AstartWindows = QtGui.QLineEdit() self.AendLabel= QtGui.QLabel("End:") self.AendWindows = QtGui.QLineEdit() self.Comparebutton = QtGui.QPushButton('Compare') #register a callback funtion - when button is pressed, we execute it self.Comparebutton.clicked.connect(self.compare) thirdLayout.addWidget(self.AstartLabel) thirdLayout.addWidget(self.AstartWindows) thirdLayout.addWidget(self.AendLabel) thirdLayout.addWidget(self.AendWindows) thirdLayout.addWidget(self.Aobj) thirdLayout.addWidget(self.comboA) thirdLayout.addWidget(self.Comparebutton) # read file from Directory self.readDir() # Display the whole GUI architecture self.mainWindow.show() #Create plot instance by plotWidget.plot() and initial the Y value for plotWidget,penStyle in zip(self.plotWidgetList,self.penStyleList): for i in range(0,self.plotNum): curve = plotWidget.plot() curve.setPen(penStyle[i]) curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ] #initial y value self.curveList.append(curve) self.curveYDataList.append(curveYData) for i in range(0,self.plotNum): curve = self.plotWidgetList[2].plot() curve.setPen(penStyle[i]) curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ] self.curveList2.append(curve) self.curveYDataList2.append(curveYData) self.SettingModel() print "init ok" self.writeout = True self.logfp = open('log.txt', "w") self.timeLogfp = open('Timelog.txt', "w") def SettingModel(self): '''load model here''' pass def close(self): self.app.closeAllWindows() self.app.quit() def ResetGraph(self): for i in range(0, len(self.curveYDataList) ): self.curveYDataList[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ] for i in range(0, len(self.curveYDataList2) ): self.curveYDataList2[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ] self.dataListLen = [] self.dataTotolLen = 0 try: self.plotWidgetList[0].removeItem(self.ROI1) self.plotWidgetList[1].removeItem(self.ROI2) except: pass self.ROI1 = None self.ROI2 = None def RegionWindows(self,upBbound): axes = ['X','Y','Z'] Dirs = ['P2N','N2P'] ret = {} ret['X'] ={} ret['Y'] ={} ret['Z'] ={} ret['X']['N2P'] = [] ret['X']['P2N'] = [] ret['Y']['N2P'] = [] ret['Y']['P2N'] = [] ret['Z']['N2P'] = [] ret['Z']['P2N'] = [] for axis in axes: for Dir in Dirs: for boundry in self.windowsCrossDataIndex[axis][Dir]: if boundry[1] > upBbound: break else: ret[axis][Dir].append(boundry) return ret def GetInfo(self,ret): axes = ['X','Y','Z'] Dirs = ['P2N','N2P'] pos = {} pos['X'] =[0,1] pos['Y'] =[1,2] pos['Z'] =[2,3] for axis in axes: for Dir in Dirs: # print axis,Dir,"------------------------" for idx in ret[axis][Dir]: if idx[1] - idx[0] < 40: # print idx[0],idx[1],"not enough" idx.append("not enough") else: # print idx[0],idx[1],np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) if np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) < 0.15: idx.append(None) # print np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) else: idx.append(np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) ) def DrawPic(self): self.ResetGraph() startWindowsIdx = int(self.startWindows.text()) endWindowsIdx = int(self.endWindows.text()) startIDX = self.workingIdx[startWindowsIdx][0] endIDX = self.workingIdx[endWindowsIdx][1] #start:stop:step ret = self.RegionWindows(endIDX) print ret,endIDX dataList = np.concatenate((self.Acc[startIDX:endIDX,:],self.Angle[startIDX:endIDX,:]),axis=1) # print "scipy.stats.skewtest:",scipy.stats.skewtest(self.Acc[startIDX:endIDX,:],axis=0) # print "mean:",np.mean( self.Acc[self.workingIdx[endWindowsIdx][0]:endIDX,:] ,axis=0) # print "start angle:",self.Angle[startIDX,:],"Last angle:",self.Angle[endIDX-1,:] # print "local Min X:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,0:1] ,axis=0)[0],"local Min Y:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,1:2] ,axis=0)[0],"local Min Z:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,2:3] ,axis=0)[0] # print "local Max X:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,0:1] ,axis=0)[0],"local Max Y:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,1:2] ,axis=0)[0],"local Max Z:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,2:3] ,axis=0)[0] dataList = dataList[::self.ScalerNum,:] self.GetInfo(ret) dataList = dataList.transpose() self.ROI1 = pg.LinearRegionItem([startIDX,endIDX]) self.ROI2 = pg.LinearRegionItem([startIDX,endIDX]) self.plotWidgetList[0].addItem(self.ROI1) self.plotWidgetList[1].addItem(self.ROI2) # print endIDX-startIDX,dataList.shape for data,curve,yData,i in zip (dataList,self.curveList2,self.curveYDataList2 ,range(0,7)): # print len(yData) yData[0:dataList.shape[1]] = dataList[i,:].tolist()[0] # print len(dataList[i,:].tolist()) curve.setData(y=yData, x=self.curveXData) self.app.processEvents() def diffAngle(self,data): ret = np.mat([0.0,0.0,0.0]) for i,j in zip(range(0,data.shape[0]-1), range(1,data.shape[0]) ): ret =np.concatenate ( (ret,data[j,:]-data[i,:]),axis=0 ) return ret def ReadFile(self): self.ResetGraph() self.filename = str(self.fileInputName.currentText()) self.FileJudge(self.filename,paint=True) def FileJudge(self,filename,paint=False,writeout=False): print filename,DirSetting,ComplexDirSetting if writeout==True: self.logfp.write(filename+ ' '+DirSetting+'\n') try: fp = open(ComplexDirSetting+filename, "rb") except: fp = open(DirSetting+filename, "rb") tempDict = pickle.load(fp) # print tempDict self.filteredIdx = tempDict['filteredIdx'] self.Acc = tempDict['Acc'] self.Gyo = tempDict['Gyo'] self.Mag = tempDict['Mag'] self.Angle = tempDict['Angle'] # self.Angle = self.Angle - np.mean(self.Angle,axis=1) self.windowsCrossDataIndex = tempDict['windowsCrossDataIndex'] self.AccRawState = tempDict['AccRawState'] self.GyoRawState = tempDict['GyoRawStata'] self.workingIdx = tempDict['workingIdx'] self.MayBeValid = [] self.VarDataIdx = tempDict['VarDataIdx'] self.seq = tempDict['seq'] self.timestamp = tempDict['timestamp'] offset = self.workingIdx[0][0] for i in range (0,len(self.workingIdx)): self.workingIdx[i][0] = self.workingIdx[i][0] - offset self.workingIdx[i][1] = self.workingIdx[i][1] - offset for axis in ['X','Y','Z']: for Dir in ['N2P','P2N']: for i in range(0,len(self.windowsCrossDataIndex[axis][Dir])): self.windowsCrossDataIndex[axis][Dir][i][0] = self.windowsCrossDataIndex[axis][Dir][i][0] - offset self.windowsCrossDataIndex[axis][Dir][i][1] = self.windowsCrossDataIndex[axis][Dir][i][1] - offset # self.windowsCrossDataIndex = self.getCrossingWindowsIDX(self.Acc) else: self.logfp.write("workingIdx:"+str(len(self.workingIdx))+'\n') startIDX = self.workingIdx[0][0] endIDX = self.workingIdx[-1][1] dataList = np.concatenate((self.Acc,self.Angle),axis=1) dataList = dataList.transpose() if paint == True: # Plot Data for data,curve,yData,i in zip (dataList,self.curveList,self.curveYDataList ,range(0,7)): # print len(yData) yData[0:endIDX-startIDX] = dataList[i,:].tolist()[0] # print len(dataList[i,:].tolist()) curve.setData(y=yData, x=self.curveXData) self.app.processEvents() # classify or somewhat you can implement in Judge function self.Judge() def readDir(self): ''' read Dir and catch all file contained the keywords which defined in complexG & keywords''' global DirSetting,ComplexDirSetting,Name self.fileList = [] complexG =['ForwardBackward','BackwardForward','DownUp','UpDown','RightLeft','LeftRight','LeftForward','RightForward','UpRight','UpLeft','RightUpForward','ForwardRight','V','VII','LeftbackForward','RightbackForward','ForwardLeft','LeftLeftForward','RightRightForward','ForwardUp','DownBackward','DownLeft','DownRight','ForwardBackwardForward','LeftRightUp','BackwardRightLeftforward','DownLeftRightforward','RightUpForward'] keywords = ['GoStraight','BackStraight','DownStraight','UpStraight','LeftStraight','RightStraight','RightUpStraight','LeftGoStraight','RightGoStraight','LeftBackStraight','RightBackStraight'] for i in range (0,len(complexG)): complexG[i] = Name + complexG[i] for i in range (0,len(keywords)): keywords[i] = Name + keywords[i] for keyword in complexG: for fileName in listdir(ComplexDirSetting): # if keyword == 'Circle':s # print fileName,fileName[0:len(keyword)] if keyword in fileName[0:len(keyword)]: if fileName not in self.fileList: self.fileList.append(fileName) for keyword in keywords: for fileName in listdir(DirSetting): # if keyword == 'Circle':s # print fileName,fileName[0:len(keyword)] if keyword in fileName[0:len(keyword)]: if fileName not in self.fileList: self.fileList.append(fileName) self.fileInputName.addItems(self.fileList) self.comboA.addItems(self.fileList) def Judge(self,writeout=False): pass # print "\033[1;31m",data[3],"len:",data[2] - data[1] + 1 ,data[2],data[1],"\033[1;m" # print "Dis:",disOrder # print "Angle:",angleOrder def compare(self): startWindowsIdx = int(self.startWindows.text()) endWindowsIdx = int(self.endWindows.text()) startIDX = self.workingIdx[startWindowsIdx][0] endIDX = self.workingIdx[endWindowsIdx][1] AstartWindowsIdx = None AendWindowsIdx = None AstartIDX = None AendIDX = None try: AstartWindowsIdx = int(self.AstartWindows.text()) AendWindowsIdx = int(self.AendWindows.text()) except: pass filename = str(self.comboA.currentText()) try: fp = open(DirSetting+filename, "rb") except: fp = open(ComplexDirSetting+filename, "rb") tempDict = pickle.load(fp) Acc = tempDict['Acc'] Gyo = tempDict['Gyo'] Mag = tempDict['Mag'] Angle = tempDict['Angle'] windowsCrossDataIndex = tempDict['windowsCrossDataIndex'] AccRawState = tempDict['AccRawState'] GyoRawState = tempDict['GyoRawStata'] workingIdx = tempDict['workingIdx'] VarDataIdx = tempDict['VarDataIdx'] seq = tempDict['seq'] timestamp = tempDict['timestamp'] AstartIDX = workingIdx[AstartWindowsIdx][0] AendIDX = workingIdx[AendWindowsIdx][1] print startWindowsIdx,endWindowsIdx,AstartWindowsIdx,AendWindowsIdx if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): #QtGui.QApplication.instance().exec_() A = MyRealTimePlot() # A.update() A.app.instance().exec_() # QtGui.QApplication.instance().exec_() # def cross_correlation_using_fft(x, y): # f1 = fft(x) # f2 = fft(np.flipud(y)) # cc = np.real(ifft(f1 * f2)) # return fftshift(cc) # # print self.windowsCrossDataIndex # # for gesture in FinalS: # # print "\033[1;31m",gesture,"\033[1;m" # def compute_shift(x, y): # assert len(x) == len(y) # c = cross_correlation_using_fft(x, y) # assert len(c) == len(x) # zero_index = int(len(x) / 2) - 1 # shift = zero_index - np.argmax(c) # return shift
MyRealTimePlot
identifier_name