Best Gauge code snippet using reporter.getTable
schema_fetch.go
Source:schema_fetch.go
1// Copyright (c) 2017-2018 Uber Technologies, Inc.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package metastore15import (16 "fmt"17 controllerCli "github.com/uber/aresdb/controller/client"18 controllerMutatorCom "github.com/uber/aresdb/controller/mutators/common"19 memCom "github.com/uber/aresdb/memstore/common"20 "github.com/uber/aresdb/metastore/common"21 "github.com/uber/aresdb/utils"22 "reflect"23 "time"24)25// SchemaFetchJob is a job that periodically pings ares-controller and updates table schemas if applicable26type SchemaFetchJob struct {27 clusterName string28 hash string29 intervalInSeconds int30 schemaMutator common.TableSchemaMutator31 enumUpdater memCom.EnumUpdater32 schemaValidator TableSchemaValidator33 controllerClient controllerCli.ControllerClient34 enumMutator controllerMutatorCom.EnumMutator35 stopChan chan struct{}36}37// NewSchemaFetchJob creates a new SchemaFetchJob38func NewSchemaFetchJob(intervalInSeconds int, schemaMutator common.TableSchemaMutator, enumUpdater memCom.EnumUpdater, schemaValidator TableSchemaValidator, controllerClient controllerCli.ControllerClient, enumMutator controllerMutatorCom.EnumMutator, clusterName, initialHash string) *SchemaFetchJob {39 return &SchemaFetchJob{40 clusterName: clusterName,41 hash: initialHash,42 intervalInSeconds: intervalInSeconds,43 schemaMutator: schemaMutator,44 enumUpdater: enumUpdater,45 schemaValidator: schemaValidator,46 stopChan: make(chan struct{}),47 controllerClient: controllerClient,48 enumMutator: enumMutator,49 }50}51// Run starts the scheduling52func (j *SchemaFetchJob) Run() {53 tickChan := time.NewTicker(time.Second * time.Duration(j.intervalInSeconds)).C54 for {55 select {56 case <-tickChan:57 j.FetchSchema()58 if j.enumUpdater != nil {59 j.FetchEnum()60 }61 case <-j.stopChan:62 return63 }64 }65}66// Stop stops the scheduling67func (j *SchemaFetchJob) Stop() {68 close(j.stopChan)69}70func (j *SchemaFetchJob) FetchSchema() {71 newHash, err := j.controllerClient.GetSchemaHash(j.clusterName)72 if err != nil {73 reportError(err, true, "hash")74 return75 }76 if newHash != j.hash {77 newSchemas, err := j.controllerClient.GetAllSchema(j.clusterName)78 if err != nil {79 reportError(err, true, "allSchema")80 return81 }82 err = j.applySchemaChange(newSchemas)83 if err != nil {84 // errors already reported, just return without updating hash85 return86 }87 j.hash = newHash88 }89 utils.GetLogger().Debug("Succeeded to run schema fetch job")90 utils.GetRootReporter().GetCounter(utils.SchemaFetchSuccess).Inc(1)91}92func (j *SchemaFetchJob) applySchemaChange(tables []common.Table) (err error) {93 oldTables, err := j.schemaMutator.ListTables()94 if err != nil {95 return96 }97 oldTablesMap := make(map[string]bool)98 for _, oldTableName := range oldTables {99 oldTablesMap[oldTableName] = true100 }101 for _, table := range tables {102 if _, exist := oldTablesMap[table.Name]; !exist {103 // found new table104 err = j.schemaMutator.CreateTable(&table)105 if err != nil {106 reportError(err, true, table.Name)107 continue108 }109 utils.GetRootReporter().GetCounter(utils.SchemaCreationCount).Inc(1)110 utils.GetLogger().With("table", table.Name).Info("added new table")111 } else {112 oldTablesMap[table.Name] = false113 var oldTable *common.Table114 oldTable, err = j.schemaMutator.GetTable(table.Name)115 if err != nil {116 reportError(err, true, table.Name)117 continue118 }119 if oldTable.Incarnation < table.Incarnation {120 // found new table incarnation, delete previous table and data121 // then create new table122 err := j.schemaMutator.DeleteTable(table.Name)123 if err != nil {124 reportError(err, true, table.Name)125 continue126 }127 utils.GetRootReporter().GetCounter(utils.SchemaDeletionCount).Inc(1)128 utils.GetLogger().With("table", table.Name).Info("deleted table")129 err = j.schemaMutator.CreateTable(&table)130 if err != nil {131 reportError(err, true, table.Name)132 continue133 }134 utils.GetRootReporter().GetCounter(utils.SchemaCreationCount).Inc(1)135 utils.GetLogger().With("table", table.Name).Info("recreated table")136 } else if oldTable.Incarnation == table.Incarnation && !reflect.DeepEqual(&table, oldTable) {137 // found table update138 j.schemaValidator.SetNewTable(table)139 j.schemaValidator.SetOldTable(*oldTable)140 err = j.schemaValidator.Validate()141 if err != nil {142 reportError(err, true, table.Name)143 continue144 }145 err = j.schemaMutator.UpdateTable(table)146 if err != nil {147 reportError(err, true, table.Name)148 continue149 }150 utils.GetRootReporter().GetCounter(utils.SchemaUpdateCount).Inc(1)151 utils.GetLogger().With("table", table.Name).Info("updated table")152 }153 }154 }155 for oldTableName, notAddressed := range oldTablesMap {156 if notAddressed {157 // found table deletion158 err = j.schemaMutator.DeleteTable(oldTableName)159 if err != nil {160 reportError(err, true, oldTableName)161 continue162 }163 utils.GetRootReporter().GetCounter(utils.SchemaDeletionCount).Inc(1)164 }165 }166 return167}168// FetchEnum updates all enums169func (j *SchemaFetchJob) FetchEnum() {170 var (171 tableNames []string172 table *common.Table173 enumCases []string174 err error175 )176 tableNames, err = j.schemaMutator.ListTables()177 if err != nil {178 reportError(err, false, "failed to get tables when fetching enums")179 return180 }181 for _, tableName := range tableNames {182 table, err = j.schemaMutator.GetTable(tableName)183 if err != nil {184 reportError(err, false, fmt.Sprintf("failed to get table %s when fetching enums", tableName))185 continue186 }187 for _, column := range table.Columns {188 if !column.IsEnumBasedColumn() {189 continue190 }191 enumCases, err = j.enumMutator.GetEnumCases(j.clusterName, tableName, column.Name)192 if err != nil {193 reportError(err, false, fmt.Sprintf("failed to get enums, table %s column %s", tableName, column.Name))194 continue195 }196 err = j.enumUpdater.UpdateEnum(tableName, column.Name, enumCases)197 if err != nil {198 reportError(err, false, fmt.Sprintf("failed to update enums, table %s column %s", tableName, column.Name))199 continue200 }201 utils.GetLogger().Debugf("Succeeded to fetch enums. table %s, column %s", tableName, column.Name)202 }203 }204}205func reportError(err error, isSchemaError bool, extraInfo string) {206 if isSchemaError {207 utils.GetRootReporter().GetCounter(utils.SchemaFetchFailure).Inc(1)208 } else {209 utils.GetRootReporter().GetCounter(utils.SchemaFetchFailureEnum).Inc(1)210 }211 utils.GetLogger().With("extraInfo", extraInfo).Error(utils.StackError(err, "err running schema fetch job"))212}...
api_alertmanager_guards.go
Source:api_alertmanager_guards.go
1package api2import (3 "fmt"4 "github.com/google/go-cmp/cmp"5 "github.com/google/go-cmp/cmp/cmpopts"6 apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"7 ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"8 "github.com/grafana/grafana/pkg/util/cmputil"9 amConfig "github.com/prometheus/alertmanager/config"10 "github.com/prometheus/alertmanager/pkg/labels"11)12func (srv AlertmanagerSrv) provenanceGuard(currentConfig apimodels.GettableUserConfig, newConfig apimodels.PostableUserConfig) error {13 if err := checkRoutes(currentConfig, newConfig); err != nil {14 return err15 }16 if err := checkTemplates(currentConfig, newConfig); err != nil {17 return err18 }19 if err := checkContactPoints(currentConfig.AlertmanagerConfig.Receivers, newConfig.AlertmanagerConfig.Receivers); err != nil {20 return err21 }22 if err := checkMuteTimes(currentConfig, newConfig); err != nil {23 return err24 }25 return nil26}27func checkRoutes(currentConfig apimodels.GettableUserConfig, newConfig apimodels.PostableUserConfig) error {28 reporter := cmputil.DiffReporter{}29 options := []cmp.Option{cmp.Reporter(&reporter), cmpopts.EquateEmpty(), cmpopts.IgnoreUnexported(labels.Matcher{})}30 routesEqual := cmp.Equal(currentConfig.AlertmanagerConfig.Route, newConfig.AlertmanagerConfig.Route, options...)31 if !routesEqual && currentConfig.AlertmanagerConfig.Route.Provenance != ngmodels.ProvenanceNone {32 return fmt.Errorf("policies were provisioned and cannot be changed through the UI")33 }34 return nil35}36func checkTemplates(currentConfig apimodels.GettableUserConfig, newConfig apimodels.PostableUserConfig) error {37 for name, template := range currentConfig.TemplateFiles {38 provenance := ngmodels.ProvenanceNone39 if prov, present := currentConfig.TemplateFileProvenances[name]; present {40 provenance = prov41 }42 if provenance == ngmodels.ProvenanceNone {43 continue // we are only interested in non none44 }45 found := false46 for newName, newTemplate := range newConfig.TemplateFiles {47 if name != newName {48 continue49 }50 found = true51 if template != newTemplate {52 return fmt.Errorf("cannot save provisioned template '%s'", name)53 }54 break // we found the template and we can proceed55 }56 if !found {57 return fmt.Errorf("cannot delete provisioned template '%s'", name)58 }59 }60 return nil61}62func checkContactPoints(currReceivers []*apimodels.GettableApiReceiver, newReceivers []*apimodels.PostableApiReceiver) error {63 newCPs := make(map[string]*apimodels.PostableGrafanaReceiver)64 for _, postedReceiver := range newReceivers {65 for _, postedContactPoint := range postedReceiver.GrafanaManagedReceivers {66 newCPs[postedContactPoint.UID] = postedContactPoint67 }68 }69 for _, existingReceiver := range currReceivers {70 for _, contactPoint := range existingReceiver.GrafanaManagedReceivers {71 if contactPoint.Provenance == ngmodels.ProvenanceNone {72 continue // we are only interested in non none73 }74 postedContactPoint, present := newCPs[contactPoint.UID]75 if !present {76 return fmt.Errorf("cannot delete provisioned contact point '%s'", contactPoint.Name)77 }78 editErr := fmt.Errorf("cannot save provisioned contact point '%s'", contactPoint.Name)79 if contactPoint.DisableResolveMessage != postedContactPoint.DisableResolveMessage {80 return editErr81 }82 if contactPoint.Name != postedContactPoint.Name {83 return editErr84 }85 if contactPoint.Type != postedContactPoint.Type {86 return editErr87 }88 for key := range contactPoint.SecureFields {89 if value, present := postedContactPoint.SecureSettings[key]; present && value != "" {90 return editErr91 }92 }93 existingSettings, err := contactPoint.Settings.Map()94 if err != nil {95 return err96 }97 newSettings, err := postedContactPoint.Settings.Map()98 if err != nil {99 return err100 }101 for key, val := range existingSettings {102 if newVal, present := newSettings[key]; present {103 if val != newVal {104 return editErr105 }106 } else {107 return editErr108 }109 }110 }111 }112 return nil113}114func checkMuteTimes(currentConfig apimodels.GettableUserConfig, newConfig apimodels.PostableUserConfig) error {115 newMTs := make(map[string]amConfig.MuteTimeInterval)116 for _, newMuteTime := range newConfig.AlertmanagerConfig.MuteTimeIntervals {117 newMTs[newMuteTime.Name] = newMuteTime118 }119 for _, muteTime := range currentConfig.AlertmanagerConfig.MuteTimeIntervals {120 provenance := ngmodels.ProvenanceNone121 if prov, present := currentConfig.AlertmanagerConfig.MuteTimeProvenances[muteTime.Name]; present {122 provenance = prov123 }124 if provenance == ngmodels.ProvenanceNone {125 continue // we are only interested in non none126 }127 postedMT, present := newMTs[muteTime.Name]128 if !present {129 return fmt.Errorf("cannot delete provisioned mute time '%s'", muteTime.Name)130 }131 reporter := cmputil.DiffReporter{}132 options := []cmp.Option{cmp.Reporter(&reporter), cmpopts.EquateEmpty()}133 timesEqual := cmp.Equal(muteTime.TimeIntervals, postedMT.TimeIntervals, options...)134 if !timesEqual {135 return fmt.Errorf("cannot save provisioned mute time '%s'", muteTime.Name)136 }137 }138 return nil139}...
summary_table_test.go
Source:summary_table_test.go
...24 doc, err := helper.ParseXML(buf.Bytes())25 Expect(err).ToNot(HaveOccurred())26 return doc27}28func getTable(control string) xml.Node {29 doc := docFixture(control)30 // replicate what ssp.Document's SummaryTables() method is doing, except that this source isn't a full Word doc31 tables, err := doc.Search(ssp.SummaryTablesXPath)32 Expect(err).NotTo(HaveOccurred())33 return tables[0]34}35var _ = Describe("SummaryTable", func() {36 Describe("Fill", func() {37 It("fills in the Responsible Role for controls", func() {38 table := getTable("AC-2")39 st, err := NewSummaryTable(table)40 Expect(err).NotTo(HaveOccurred())41 openControlData := fixtures.LoadOpenControlFixture()42 st.Fill(openControlData)43 Expect(table.Content()).To(ContainSubstring(`Responsible Role: Amazon Elastic Compute Cloud: AWS Staff`))44 })45 It("fills in the Responsible Role for control enhancements", func() {46 table := getTable("AC-2 (1)")47 st, err := NewSummaryTable(table)48 Expect(err).NotTo(HaveOccurred())49 openControlData := fixtures.LoadOpenControlFixture()50 st.Fill(openControlData)51 Expect(table.Content()).To(ContainSubstring(`Responsible Role: Amazon Elastic Compute Cloud: AWS Staff`))52 })53 It("fills in the control origination", func() {54 table := getTable("AC-2")55 st, err := NewSummaryTable(table)56 Expect(err).NotTo(HaveOccurred())57 openControlData := fixtures.LoadOpenControlFixture()58 By("initially loading the summary table, we should detect that the shared control origination" +59 " is false")60 Expect(err).ToNot(HaveOccurred())61 Expect(st.originTable.origins[origin.SharedOrigination].IsChecked()).To(Equal(false))62 By("running fill, we expect the shared control origination to equal true")63 st.Fill(openControlData)64 Expect(err).ToNot(HaveOccurred())65 Expect(st.originTable.origins[origin.SharedOrigination].IsChecked()).To(Equal(true))66 })67 })68 Describe("Diff", func() {69 It("detects no diff when the value of responsible role is empty", func() {70 Skip("Revisit when we can mock the opencontroldata and really expect no diffs.")71 table := getTable("AC-2")72 st, err := NewSummaryTable(table)73 Expect(err).NotTo(HaveOccurred())74 openControlData := fixtures.LoadOpenControlFixture()75 diff, err := st.Diff(openControlData)76 Expect(diff).To(Equal([]reporter.Reporter{}))77 Expect(err).To(BeNil())78 })79 })80})...
getTable
Using AI Code Generation
1import (2func main() {3 data := [][]string{4 []string{"1", "2", "3"},5 []string{"4", "5", "6"},6 []string{"7", "8", "9"},7 }8 table := tablewriter.NewWriter(os.Stdout)9 table.SetHeader([]string{"Header1", "Header2", "Header3"})10 table.AppendBulk(data)11 table.Render()12}
getTable
Using AI Code Generation
1import (2type Reporter struct {3}4func (r *Reporter) getTable() string {5}6func main() {7 r := Reporter{}8 fmt.Println(r.getTable())9 fmt.Println(r.getTable())10 fmt.Println(r.getTable())11 fmt.Println(r.getTable())12}
getTable
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handler)4 http.HandleFunc("/report", report)5 log.Fatal(http.ListenAndServe("localhost:8000", nil))6}7func handler(w http.ResponseWriter, r *http.Request) {8 fmt.Fprintf(w, "
getTable
Using AI Code Generation
1import (2func main() {3 reporter := Reporter{}4 reporter.addGame("Lions 3, Snakes 3")5 reporter.addGame("Tarantulas 1, FC Awesome 0")6 reporter.addGame("Lions 1, FC Awesome 1")7 reporter.addGame("Tarantulas 3, Snakes 1")8 reporter.addGame("Lions 4, Grouches 0")9 fmt.Println(reporter.getTable())10}11import (12func main() {13 reporter := Reporter{}14 reporter.addGame("Lions 3, Snakes 3")15 reporter.addGame("Tarantulas 1, FC Awesome 0")16 reporter.addGame("Lions 1, FC Awesome 1")17 reporter.addGame("Tarantulas 3, Snakes 1")18 reporter.addGame("Lions 4, Grouches 0")19 fmt.Println(reporter.getTable())20}21import (22func main() {23 reporter := Reporter{}24 reporter.addGame("Lions 3, Snakes 3")25 reporter.addGame("Tarantulas 1, FC Awesome 0")26 reporter.addGame("Lions 1, FC Awesome 1")27 reporter.addGame("Tarantulas 3, Snakes 1")28 reporter.addGame("Lions 4, Grouches 0")29 fmt.Println(reporter.getTable())30}31import (
getTable
Using AI Code Generation
1import (2type reporter struct {3}4func (r reporter) getTable() string {5}6func main() {7 r := reporter{age: 20}8 fmt.Println(reflect.TypeOf(r).MethodByName("getTable").Call([]reflect.Value{}))9}
getTable
Using AI Code Generation
1import (2func main() {3 reporter := Reporter{}4 reporter.getTable()5}6import (7type Reporter struct {8}9func (reporter *Reporter) getTable() {10 table := Table{}11 table.getRows()12}13import (14type Table struct {15}16func (table *Table) getRows() {17 row := Row{}18 row.getCells()19}20import (21type Row struct {22}23func (row *Row) getCells() {24 cell := Cell{}25 cell.getValues()26}27import (28type Cell struct {29}30func (cell *Cell) getValues() {31 value := Value{}32 value.getValue()33}34import (35type Value struct {36}37func (value *Value) getValue() {38 fmt.Println("Value")39}40In the above example, we have created a Reporter class and it has a method getTable() which is used to create an instance of Table class and call getRows() method of Table class. Similarly, we have created a Table class and it has a method getRows() which is used to create an instance of Row class
getTable
Using AI Code Generation
1import (2func main() {3 reporter := reporter{}4 table := table{}5 table.addRow("a", "b")6 table.addRow("c", "d")7 table.addRow("e", "f")8 reporter.addTable(table)9 reportedTable := reporter.getTable()10 fmt.Println(reportedTable)11}12import (13type table struct {14}15func (t *table) addRow(row ...string) {16 t.rows = append(t.rows, row)17}18func (t *table) String() string {19 for _, row := range t.rows {20 tableString += fmt.Sprintf("%v21 }22}23import (24type reporter struct {25}26func (r *reporter) addTable(table table) {27 r.tables = append(r.tables, table)28}29func (r *reporter) getTable() table {30}31import (32type Table struct {33}34func (t *Table) addRow(row ...string) {35 t.Rows = append(t.Rows, row)36}37func (t *Table) String() string {38 for _, row := range t.Rows {39 tableString += fmt.Sprintf("%v40 }41}
getTable
Using AI Code Generation
1import (2func main() {3 if len(os.Args) == 1 {4 fmt.Println("Enter the file name")5 fmt.Scanln(&filename)6 } else {7 }8 reporter := new(Reporter)9 table := reporter.getTable(filename)10 fmt.Println(table)11}12import (13func main() {14 if len(os.Args) == 1 {15 fmt.Println("Enter the file name")16 fmt.Scanln(&filename)17 } else {18 }19 reporter := new(Reporter)20 table := reporter.getTable(filename)21 fmt.Println(table)22}23import (24func main() {25 if len(os.Args) == 1 {26 fmt.Println("Enter the file name")27 fmt.Scanln(&filename)28 } else {29 }30 reporter := new(Reporter)31 table := reporter.getTable(filename)32 fmt.Println(table)33}34import (35func main() {36 if len(os.Args) == 1 {37 fmt.Println("Enter the file name")38 fmt.Scanln(&filename)39 } else {40 }41 reporter := new(Reporter)42 table := reporter.getTable(filename)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!